模板邮件发送
我们假设发送给用户一封激活邮件
1.添加依赖:
1 <!--添加thymeleaf依赖 --> 2 <dependency> 3 <groupId>org.springframework.boot</groupId> 4 <artifactId>spring-boot-starter-thymeleaf</artifactId> 5 </dependency>
2.添加模板:
1 <!DOCTYPE html> 2 <html lang="zh" xmlns:th="http://www.thymeleaf.org"> 3 <head> 4 <meta charset="UTF-8" > 5 <title>账号激活邮件</title> 6 </head> 7 <body> 8 您好,这是验证邮件,请点击下面的链接完成验证,<br/> 9 <a href="#" th:href="@{ http://www.xm.com/eamil/{id}(id=${id}) }">激活账号</a> 10 </body> 11 </html>
资料分享 学习群:642461309
3.定义发送模板邮件业务接口:
1 /** 2 * 发送模板邮件 3 * @param to:收件人 4 * @param subject: 标题 5 * @param info:模板名 6 */ 7 void sendTemplateMail(String to,String subject,String info);
4.实现发送模板邮件业务:
实现过程:
(1)实现接口
(2)定义模板解析器
(3)定义参数
(4)绑定参数到模板
(6)解析模板为字符串
(6)封装信件
(7)发送邮件
1 package com.xm.service.impl; 2 3 import java.io.File; 4 5 import javax.mail.MessagingException; 6 import javax.mail.internet.MimeMessage; 7 8 import org.springframework.beans.factory.annotation.Autowired; 9 import org.springframework.beans.factory.annotation.Value; 10 import org.springframework.mail.SimpleMailMessage; 11 import org.springframework.mail.javamail.JavaMailSender; 12 import org.springframework.mail.javamail.MimeMessageHelper; 13 import org.springframework.stereotype.Service; 14 import org.thymeleaf.TemplateEngine; 15 import org.thymeleaf.context.Context; 16 17 import com.xm.service.EmailService; 18 /** 19 * 邮件发送业务实现 20 * @author xm 21 * 22 */ 23 @Service 24 public class EmailServiceImpl implements EmailService { 25 26 //获取发送者信息 27 @Value("${mail.from.addr}") 28 private String from; 29 30 //定义邮件发送者 31 @Autowired 32 private JavaMailSender sender; 33 34 @Autowired 35 //模板解析 36 private TemplateEngine templateEngine; 37 38 39 40 @Override 41 public void sendTemplateMail(String to, String subject, String info) { 42 //创建多用途互联网邮件 43 MimeMessage message = sender.createMimeMessage(); 44 45 try { 46 //封装多用途互联网邮件 47 MimeMessageHelper helper = new MimeMessageHelper(message, true); 48 helper.setFrom(from); 49 helper.setTo(to); 50 helper.setSubject(subject); 51 //封装模板参数 52 Context context = new Context(); 53 context.setVariable("id", 1); 54 //解析模板 55 String content = templateEngine.process(info, context); 56 57 //true:识别Html 58 helper.setText(content, true); 59 60 } catch (Exception e) { 61 e.printStackTrace(); 62 } 63 sender.send(message); 64 } 65 66 }
5.定义测试:
1 @Test 2 /** 3 * 发送模板邮件 4 */ 5 public void sendTemplateMail() { 6 emailService.sendTemplateMail("1373572467@qq.com", "激活邮件","EmailActivation"); 7 }
测试结果截图: