- 需求:批量发送邮件,用户可能看到其他用户的邮箱地址,之前用BBC发送,但问题是接收地址是同一个。
- 官方解决方案:https://sendgrid.kke.co.jp/docs/Tutorials/A_Transaction_Mail/send_with_substitution.html
- 注意:最大发送数量问题
- 在springboot2中的代码实现
private void sendMany(List<String> lstAddress, String mailFrom,String subject, String text,String API_KEY) {
try{
Email from = new Email(mailFrom);
Mail mail = new Mail();
for (String mailto : lstAddress) {
Email to = new Email(mailto);
Personalization personalization = new Personalization();
personalization.addTo(to);
personalization.addSubstitution("-name-", mailto);
mail.addPersonalization(personalization);
}
mail.setFrom(from);
mail.setSubject(subject);
Content content = new Content("text/plain", text);
mail.addContent(content);
SendGrid sg = new SendGrid(API_KEY);
Request request = new Request();
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
Response response = sg.api(request);
}catch(IOException ex){
ex.printStackTrace();
}
}
mail.build()生成的JSON结构如下:
{ "to" : [ "alice@test.com", "bob@test.com" ], "sub": { "-name-": [ "アリス", "ボブ" ] }