使用定制邮件模板的方法实现通用邮件发送,Thymeleaf构建邮件模板需要一起导入依赖。
3.配置文件yml添加邮件服务配置org.springframework.boot spring-boot-starter-mailorg.springframework.boot spring-boot-starter-thymeleaf
# Spring配置 spring: mail: host: smtp.qq.com username: ********@qq.com # password是第一步QQ邮箱开通的smtp服务后得到的客户端授权码 password: ****************** default-encoding: UTF-8 properties: mail: smtp: auth: true starttls: enable: true required: true #thymeleaf模板引擎配置太简单,就不贴出来了4.编写接口IMailService
public interface IMailService { void sendHtmlMailThymeLeaf(String mailFrom, String mailFromNick, String mailTo, String cc, String subject, String content); }5.编写实现MailServiceImpl
@Service public class MailServiceImpl implements IMailService { @Autowired private JavaMailSender mailSender; @Override public void sendHtmlMailThymeLeaf(String mailFrom, String mailFromNick, String mailTo, String cc, String subject, String content) { MimeMessage mimeMessage = mailSender.createMimeMessage(); try { MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); mimeMessageHelper.setFrom(new InternetAddress(mailFromNick + " <" + mailFrom + ">")); // 设置多个收件人 String[] toAddress = mailTo.split(","); mimeMessageHelper.setTo(toAddress); if (!StringUtils.isEmpty(cc)) { mimeMessageHelper.setCc(cc); } mimeMessageHelper.setSubject(subject); // 第二个参数为true表示邮件正文是html格式的,默认是false mimeMessageHelper.setText(content, true); mailSender.send(mimeMessage); } catch (MessagingException e) { System.out.println(e); } } }6.Controller调用
// 发件人要跟yml配置文件里填写的邮箱一致 String mailFrom = "******@qq.com"; // 收件人 String mailTo = "******@qq.com,******@qq.com"; // 抄送(可为空) String cc = "******@qq.com"; // 注入mailService @Autowired private IMailService mailService; // 注入TemplateEngine @Autowired TemplateEngine templateEngine; @RequestMapping("/other/test")//请求路径 @ResponseBody public void testMail() { //注意1:这里我是查询对应的内容,使用富文本编辑器存储html标签的内容 Strategy strategy = strategyService.selectStrategyByStrategyId(Long.valueOf(1)); Context context = new Context(); // 导包是org.thymeleaf.context //注意2:获取发送的内容传入thymeleaf模板中 context.setVariable("content", strategy.getStrategyContent()); String content = templateEngine.process("mailTemplate.html", context); //System.out.println(content); mailService.sendHtmlMailThymeLeaf(mailFrom, "定义发件人名字", mailTo, cc, "定义邮件标题", content); System.out.println("邮件发送成功"); }7.thymeleaf模板 mailTemplate.html
邮件发送 Some escaped text欢迎分享,转载请注明来源:内存溢出
评论列表(0条)