目前,我将应用程序配置为通过spring-mail发送电子邮件,我的代码如下所示:
@Autowired
private JavaMailSender sender;
.....
//send email
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,
MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
StandardCharsets.UTF_8.name());
Template template = freemarkerConfig.getTemplate(templateFileName);
String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, props);
helper.setTo(to);
helper.setText(html, true);
helper.setSubject(subject);
helper.setFrom(from);
sender.send(message);
现在我有使用sendGrid重写它的任务。
我用Google搜索了这个主题,发现java有像this这样的sendGrid api:
import com.sendgrid.*;
public class SendGridExample {
public static void main(String[] args) {
SendGrid sendgrid = new SendGrid("SENDGRID_APIKEY");
SendGrid.Email email = new SendGrid.Email();
email.addTo("test@sendgrid.com");
email.setFrom("you@youremail.com");
email.setSubject("Sending with SendGrid is Fun");
email.setHtml("and easy to do anywhere, even with Java");
SendGrid.Response response = sendgrid.send(email);
}
}
我也找到了以下课程:SendGridAutoConfiguration 我也遇到了there的以下片段:
# SENDGRID (SendGridAutoConfiguration)
spring.sendgrid.api-key= # SendGrid api key (alternative to username/password).
spring.sendgrid.username= # SendGrid account username.
spring.sendgrid.password= # SendGrid account password.
spring.sendgrid.proxy.host= # SendGrid proxy host.
spring.sendgrid.proxy.port= # SendGrid proxy port.
看起来spring boot已与sendGrid集成。
但我找不到这种整合的完整例子 请跟我分享一下吗?
答案 0 :(得分:4)
Spring-Boot autoconfigures SendGrid
如果它在类路径上。
将库包含为maven依赖项(请参阅https://github.com/sendgrid/sendgrid-java),例如。使用gradle:
compile 'com.sendgrid:sendgrid-java:4.1.2'
配置SendGrid属性(请参阅https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html)
# SENDGRID (SendGridAutoConfiguration)
spring.sendgrid.api-key= # SendGrid api key (alternative to username/password).
spring.sendgrid.username= # SendGrid account username.
spring.sendgrid.password= # SendGrid account password.
spring.sendgrid.proxy.host= # SendGrid proxy host. (optional)
spring.sendgrid.proxy.port= # SendGrid proxy port. (optional)
Spring Boot会自动创建SendGrid
Bean。
有关如何使用它的示例,请参阅https://github.com/sendgrid/sendgrid-java。
class SendGridMailService {
SendGrid sendGrid;
public SendGridMailService(SendGrid sendGrid) {
this.sendGrid = sendGrid;
}
void sendMail() {
Email from = new Email("test@example.com");
String subject = "Sending with SendGrid is Fun";
Email to = new Email("test@example.com");
Content content = new Content("text/plain", "and easy to do anywhere, even with Java");
Mail mail = new Mail(from, subject, to, content);
Request request = new Request();
try {
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
Response response = this.sendGrid.api(request);
sendGrid.api(request);
// ...
} catch (IOException ex) {
// ...
}
}
}