SpringBoot使用FreeMarker模板发送邮件

本文实例为大家分享了SpringBoot +Mail+FreeMarker发送邮件,供大家参考,具体内容如下

通过spirngboot 自带的mail服务及FreeMarker模板引擎,发送邮

添加依赖


 org.springframework.boot
 spring-boot-starter-freemarker


 org.springframework.boot
 spring-boot-starter-mail


 org.springframework.boot
 spring-boot-starter-web



 org.projectlombok
 lombok
 true

在application.yml文件中配置Mail信息

spring:
 mail:
 port: 25
 username: ${username}
 password: ${password}
 protocol: smtp
 default-encoding: utf-8
 host: ${host}

编写MailService服务

@Service
public class MailServiceImpl implements MailService {

 //邮件的发送者
 @Value("${spring.mail.username}")
 private String from;

 //注入MailSender
 @Autowired
 private JavaMailSender mailSender;

 //发送邮件的模板引擎
 @Autowired
 private FreeMarkerConfigurer configurer;

 /**
 * @param params 发送邮件的主题对象 object
 * @param title 邮件标题
 * @param templateName 模板名称
 */
 @Override
 public void sendMessageMail(Object params, String title, String templateName) {

 try {

  MimeMessage mimeMessage = mailSender.createMimeMessage();
  MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
  helper.setFrom(from);
  helper.setTo(InternetAddress.parse("[email protected]"));//发送给谁
  helper.setSubject("【" + title + "-" + LocalDate.now() + " " + LocalTime.now().withNano(0) + "】");//邮件标题

  Map model = new HashMap<>();
  model.put("params", params);
  try {
  Template template = configurer.getConfiguration().getTemplate(templateName);
  try {
   String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);

   helper.setText(text, true);
   mailSender.send(mimeMessage);
  } catch (TemplateException e) {
   e.printStackTrace();
  }
  } catch (IOException e) {
  e.printStackTrace();
  }
 } catch (MessagingException e) {
  e.printStackTrace();
 }
 }
}

定义发送邮件对象

发送内容为object,我这里演示一个对象,通过模板渲染方式接收内容

@Data
public class Message {

 private String messageCode;
 private String messageStatus;
 private String cause;

}

在项目templates目录新建个message.ftl文件




 
 消息通知




邮件消息通知

MessageCode MessageStatus Cause
${(params.messageCode)!""} ${(params.messageStatus)!""} ${(params.cause)!""}

测试邮件发送

新建controller类

@RestController
public class MailController {

 @Autowired
 private MailService mailService;

 @RequestMapping(value = "/sendMessage", method = RequestMethod.GET)
 public void sendMailMessage() {
 Message message = new Message();

 message.setMessageCode("MissingParameter");
 message.setMessageStatus("Failed");
 message.setCause("缺少参数,请确认");

 mailService.sendMessageMail(message, "测试消息通知", "message.ftl");
 }
}

启动服务访问 http://localhost:8080/sendMessage

查看邮箱

SpringBoot使用FreeMarker模板发送邮件_第1张图片

源码地址

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(SpringBoot使用FreeMarker模板发送邮件)