今天SpringBoot项目中用到发送邮件提醒,之前介绍过在Java、JavaMail中发送邮件,详见:https://blog.terrynow.com/2021/03/30/java-mail-smtp-send-email/ 以及在SpringMVC中发送邮件,详见:https://blog.terrynow.com/2021/07/24/java-spring-mvc-send-mail-example-include-html-inline-attachment/
SpringBoot中发送邮件更加简单了,来看下:
首先增加pom依赖
pom.xml增加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
application.properties 增加smtp邮件账号配置
smtp发送邮件的帐号具体查看邮件供应商的smtp设置文档
# 邮箱账号等相关配置 spring.mail.protocol = smtp spring.mail.host = smtp.example.com spring.mail.port = 25 spring.mail.username = [email protected] spring.mail.password = password spring.mail.test-connection = false spring.mail.properties.mail.smtp.auth = true spring.mail.properties.mail.debug = false spring.mail.default-encoding = UTF-8
使用
以上就配置好了,很简单,接下来只要在Controller或者Service中,注入JavaMailSender就可以了
下面演示纯文本邮件和复杂的html邮件,可以使用inline cid的方式插入图片,或者addAttachment发送附件等
@Controller
public class TestController {
@Autowired
JavaMailSender javaMailSender;
@RequestMapping(value = "/test_mail_text",method = RequestMethod.GET)
@ResponseBody
public String testMailText() {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom("[email protected]"); // 发件人,一般应该设置成和spring.mail.username一致
simpleMailMessage.setTo("[email protected]");// 收件人
simpleMailMessage.setSubject("台风好大"); // 邮件主题
simpleMailMessage.setText("台风好大");// 邮件内容
javaMailSender.send(simpleMailMessage);
return "test_mail_text OK";
}
@RequestMapping(value = "/test_mail_html",method = RequestMethod.GET)
@ResponseBody
public String testMailHtml() throws Exception {
String html = "<body><div><h2>测试HTML内容</h2></div></body>";
//<img src='cid:test.jpg' />内嵌图片
// String html = "<body><div><h2>测试HTML内容</h2><img src='cid:test.jpg' width='120' height='120' style='border: none; width: 120px; height: 120px;' /></div></body>";
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom("[email protected]", "我是发送方");
// if (toName != null && toName.trim().length() > 0) {
helper.setTo(new InternetAddress("[email protected]", "Terry"));
// } else {
// helper.setTo(toAddress);
// }
helper.setSubject("?台风好大");
helper.setText(html, true);
// helper.addInline("test.jpg", new File("xxx"));//发送HTML内嵌的图片
// helper.addAttachment(xxx);//发送附件
javaMailSender.send(message);
return "test_mail_html OK";
}
}
文章评论