springBoot集成邮件服务发送邮件包含附件图片富文本或Thymeleaf模板发送邮件
在实际开发中,需要有很多地方用到关联邮件发送消息,比如注册成功信息,找回密码信息,或者通过邮件发送即将过期信息等等,所使用的应用场景很多很多,下面调用JavaMailSender发送邮件,
一、邮箱配置
首先需要我们注册邮箱,并开启二级密码设置,最主要的是开启邮箱的POP3/SMTP服务,这里以网易云邮箱举例,点击设置——POP3/SMTP/IMAP
并开启授权码,类似下图,这个授权码要牢记,后面会用到
1.配置完成,新建项目,在spirngBoot工程的pom.xml中导入邮件所需依赖及其他项目所需依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
2.配置application.properties
spring.mail.host=smtp.163.com spring.mail.username=xxxxxxxxxxx@163.com spring.mail.password=IPRWWISBDJIYVSYV spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true spring.mail.default-encoding=UTF-8
host qq邮箱为smtp.qq.com 网易邮箱为smtp.163.com
username为邮箱账号
password 特别注意这里password不代表邮箱的登录密码, 而是在刚开始生成的授权码
auth 开启权限验证
starttls.enable 是否开启加密通讯
starttls.required 是否必须开启加密通讯
3.新建邮件格式实体类,以自己内容为主 发送人,主题,内容
public class EmailBean implements Serializable { private String[] receiver; private String subject; private String content;
public String[] getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = new String[] {receiver};
}
public void setReceiver(String... receiver) {
this.receiver = receiver;
}
..getter and setter }
4.新建邮件发送工具类
(1)、纯文本格式邮件
@Component public class EmailUtil { @Value("${spring.mail.username}") private String sender; @Autowired JavaMailSender javaMailSender; public void sendPlainTextMail(EmailBean emailBean){ SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); simpleMailMessage.setFrom(sender); simpleMailMessage.setTo(emailBean.getReceiver()); simpleMailMessage.setSubject(emailBean.getSubject()); simpleMailMessage.setText(emailBean.getContent()); javaMailSender.send(simpleMailMessage); } }
测试类调用
@Autowired EmailUtil emailUtil; @Test public void sendMail(){ EmailBean emailBean = new EmailBean(); emailBean.setReceiver("xxxx@qq.com"); emailBean.setSubject("springBoot发送纯文本邮件测试"); emailBean.setContent("这是一段纯文本格式的邮件"); emailUtil.sendPlainTextMail(emailBean); }
测试执行,最终执行结果
发送邮件给多人,当然这个可以用的地方不是很多,在实体类我们将接收者receiver设成数组格式,方便群发邮件
替换上一步emailBean.setReceiver()
@Test public void sendMail(){ EmailBean emailBean = new EmailBean(); String[] arrReceivers = new String[] {"xxxxx1@qq.com", "xxxxx2@qq.com"}; emailBean.setReceiver(arrReceivers); emailBean.setSubject("springBoot发送纯文本邮件测试"); emailBean.setContent("这是一段春纯文本格式的邮件,当前时间" + new Date()); emailUtil.sendPlainTextMail(emailBean); logger.warn(String.format("发送邮件给%s成功", Arrays.toString(arrReceivers))); }
结果
(2)发送带有HTML代码的邮件发送
可以看到我们使用的JavaMailSender继承了MailSender,发送纯文本格式的使用SimpleMailMessage
而发送带有附件信息或者富文本格式的邮件我们需要使用MimeMessage
在上一步EmailUtils.java里添加方法
public void sendMimeMail(EmailBean emailBean) throws MessagingException { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); mimeMessageHelper.setFrom(sender); mimeMessageHelper.setTo(emailBean.getReceiver()); mimeMessageHelper.setSubject(emailBean.getSubject()); mimeMessageHelper.setText(emailBean.getContent(), true); javaMailSender.send(mimeMessage); }
进行测试
@Test
public void sendMimeEmail() throws MessagingException {
EmailBean emailBean = new EmailBean();
emailBean.setReceiver("xxxxxx@qq.com");
emailBean.setSubject("springBoot发送HTML格式邮件测试");
emailBean.setContent("<h1 style='color:red'>springBoot集成邮件发送html格式邮件测试</h1>");
emailUtil.sendMimeMail(emailBean);
logger.warn("发送邮件给成功");
}
(3)html中含有图片或者将图片以正文发送邮件
html代码中的图片需要在MimeMessageHelper中添加
public void sendMimeMail(EmailBean emailBean) throws MessagingException { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); mimeMessageHelper.setFrom(sender); mimeMessageHelper.setTo(emailBean.getReceiver()); mimeMessageHelper.setSubject(emailBean.getSubject()); mimeMessageHelper.setText(emailBean.getContent(), true); FileSystemResource fileSystemResource = new FileSystemResource(new File("C:\\Users\\ThinkPad\\Desktop\\image.png")); mimeMessageHelper.addInline("image", fileSystemResource); javaMailSender.send(mimeMessage); }
这里mimeMessageHelper.addInline()中的参数表示获取资源的id和Resource
@Test public void sendMimeEmail() throws MessagingException { EmailBean emailBean = new EmailBean(); emailBean.setReceiver("xxxxxx@qq.com"); emailBean.setSubject("springBoot发送HTML包含图片邮件测试"); emailBean.setContent("<h5 style='color:red'>springBoot集成邮件发送html格式邮件测试</h5>" + "<img src='cid:image"); emailUtil.sendMimeMail(emailBean); logger.warn("发送邮件给成功"); }
点击测试
可以看到图片正常显示
(4)带有附件的邮件发送
在EmailUtil.java中添加方法
public void sendAppendMimeMail(EmailBean emailBean) throws MessagingException { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); mimeMessageHelper.setFrom(sender); mimeMessageHelper.setTo(emailBean.getReceiver()); mimeMessageHelper.setSubject(emailBean.getSubject()); mimeMessageHelper.setText(emailBean.getContent(), true); String filePath = "C:\\Users\\ThinkPad\\Desktop\\账号密码.xls"; FileSystemResource fileSystemResource = new FileSystemResource(new File(filePath)); mimeMessageHelper.addAttachment("11.xls", fileSystemResource); javaMailSender.send(mimeMessage); }
@Test public void sendAppendMimeEmail() throws MessagingException { EmailBean emailBean = new EmailBean(); emailBean.setReceiver("xxxxxx@qq.com"); emailBean.setSubject("springBoot集成邮件发送附件测试"); emailBean.setContent("<h1 style='color:red'>springBoot集成邮件发送html格式邮件及附件文件测试</h1>"); emailUtil.sendAppendMimeMail(emailBean);
logger.warn("含有附件邮件发送成功");
}
(5)使用Thymeleaf模板发送邮件
上一步我们用html代码发送邮件,就写了两行已经感觉比较麻烦了字符串的拼接和图片的上传,较复杂的内容邮件用这种方式会显得很麻烦,所有我们使用模板,需要改变的值用参数代替来达到个性化的邮件。
继续在pom.xml文件中导入Thymeleaf依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
z在templates文件夹下新建mailTemp.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body > <div style="background-color:#222222;"> <img src="http://message-center-cbc-cn.obs.cn-north-1.myhuaweicloud.com/BSS/templateImg/2019411_zh_logo.png" /> </div> <h4 th:text="|尊敬的华为云客户${username}|"></h4> 您好! <p style="text-indent:2em">您的账户余额不足50.00元,为了保证您的业务正常运行,请及时进行<a href="https://cnblogs.com/LiuFqiang">充值</a></p> <p style="text-indent:2em">感谢您对华为云的支持!</p> <hr style="margin-left: initial;width: 100%; border:1px dashed #987cb9 "> <p style="color: #999;font-size: 14px;margin-top:10px;margin-bottom:40px"> 本邮件由系统自动发送,请勿直接回复! </p> <br > <p>官方网站:<a href="https://cnblogs.com/LiuFqiang">https://cnblogs.com/LiuFqiang</a></p> <p>Wechat:15641483049</p> </body> </html>
在测试类测试:
@Autowired private TemplateEngine templateEngine; @Test public void sendHtmlEmail() throws MessagingException { Context context = new Context(); context.setVariable("username", "刘**"); String emailContent = templateEngine.process("mailTemp", context); EmailBean emailBean = new EmailBean(); emailBean.setReceiver("xxxxx@qq.com"); emailBean.setSubject("springBoot集成邮件服务"); emailBean.setContent(emailContent); emailUtil.sendMimeMail(emailBean); logger.warn("模板邮件发送成功!"); }
这里需要注意templateEmgine.process的模板路径名字一个要与template静态文件的相对应,并且模板的参数名与context.setVariable的一一对应
完结!!!