项目中经常会有这样的需求,用户注册成功,需要给用户发送一封邮件。邮件需要有一定格式和样式。本次例子中用freemarker做样式,其他的模版引擎类似。

首先Spring Boot项目,项目结构如下

在pom.xml文件中添加依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-mail</artifactId>
  4. </dependency>
  5.  
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-freemarker</artifactId>
  9. </dependency>

配置发件人信息,发件人邮箱需要开通POP3/SMTP服务,如下图(我是采用126邮箱):

然后在application.properties中添加配置文件:

然后在service层中添加MailService类,代码如下

  1. import freemarker.core.ParseException;
  2. import freemarker.template.MalformedTemplateNameException;
  3. import freemarker.template.Template;
  4. import freemarker.template.TemplateException;
  5. import freemarker.template.TemplateNotFoundException;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  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.springframework.ui.freemarker.FreeMarkerTemplateUtils;
  15. import org.springframework.util.ResourceUtils;
  16. import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
  17.  
  18. import javax.mail.MessagingException;
  19. import javax.mail.internet.MimeMessage;
  20. import java.io.File;
  21. import java.io.IOException;
  22. import java.util.HashMap;
  23. import java.util.Map;
  24.  
  25. @Service
  26. public class MailService {
  27.  
  28. private final static Logger logger = LoggerFactory.getLogger(MailService.class);
  29.  
  30. @Value("${spring.mail.username}")
  31. private String from;
  32.  
  33. @Autowired
  34. private JavaMailSender mailSender;
  35.  
  36. @Autowired
  37. private FreeMarkerConfig freeMarkerConfig;
  38.  
  39. // send simple email
  40. public String sendSimple(String to, String title, String content) {
  41. SimpleMailMessage message = new SimpleMailMessage();
  42.  
  43. message.setFrom(from);
  44. message.setTo(to);
  45. message.setSubject(title);
  46. message.setText(content);
  47.  
  48. mailSender.send(message);
  49.  
  50. logger.info("{} send email to {}", from, to);
  51. return "SUCESS";
  52. }
  53.  
  54. // send template mail
  55. public String sendTemplateMail(String to, String title) {
  56. MimeMessage mimeMessage = mailSender.createMimeMessage();
  57. MimeMessageHelper helper;
  58. try {
  59. helper = new MimeMessageHelper(mimeMessage, true);
  60.  
  61. helper.setFrom(from);
  62. helper.setTo(to);
  63. helper.setSubject(title);
  64.  
  65. Map<String, Object> model = new HashMap<>();
  66. model.put("params", from);
  67. Template template = freeMarkerConfig.getConfiguration().getTemplate("message.ftl");
  68. String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
  69.  
  70. helper.setText(text, true);
  71.  
  72. mailSender.send(mimeMessage);
  73.  
  74. } catch (MessagingException e) {
  75. e.printStackTrace();
  76. } catch (MalformedTemplateNameException e) {
  77. e.printStackTrace();
  78. } catch (ParseException e) {
  79. e.printStackTrace();
  80. } catch (TemplateNotFoundException e) {
  81. e.printStackTrace();
  82. } catch (IOException e) {
  83. e.printStackTrace();
  84. } catch (TemplateException e) {
  85. e.printStackTrace();
  86. }
  87.  
  88. return "SUCEESS";
  89. }
  90.  
  91. // send template mail with attachment
  92. public String sendAttactmentMail(String to, String title){
  93. MimeMessage mimeMessage = mailSender.createMimeMessage();
  94. MimeMessageHelper helper;
  95. try {
  96. helper = new MimeMessageHelper(mimeMessage, true);
  97.  
  98. helper.setFrom(from);
  99. helper.setTo(to);
  100. helper.setSubject(title);
  101.  
  102. // add template
  103. Map<String, Object> model = new HashMap<>();
  104. model.put("params", from);
  105. Template template = freeMarkerConfig.getConfiguration().getTemplate("message.ftl");
  106. String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
  107. helper.setText(text, true);
  108.  
  109. // add attachment
  110. File file = ResourceUtils.getFile("classpath:static/flcl.jpg");
  111. helper.addAttachment(file.getName(), file);
  112.  
  113. mailSender.send(mimeMessage);
  114.  
  115. } catch (MessagingException e) {
  116. e.printStackTrace();
  117. } catch (MalformedTemplateNameException e) {
  118. e.printStackTrace();
  119. } catch (ParseException e) {
  120. e.printStackTrace();
  121. } catch (TemplateNotFoundException e) {
  122. e.printStackTrace();
  123. } catch (IOException e) {
  124. e.printStackTrace();
  125. } catch (TemplateException e) {
  126. e.printStackTrace();
  127. }
  128. return "SUCCESS";
  129. }
  130. }

这个service中写了三个方法,三个方法的作用分别对应于:发送简单邮件、发送模版邮件、发送带附件的模版邮件

核心方法是 mailSender.send(message) ,message对象根据发送的邮件类型不同而不同,主要有MimeMessage MimeMessageHelper

发送带附件的模板邮件方式是三者中最复杂,首先创建邮件对象MimeMessage ,然后通过MimeMessage对象创建MimeMessageHelper(此对象的作用:向MimeMessage对象中填充数据的助手),通过向MimeMessageHelper对象中添加一些属性,例如发件人、收件人、邮件主题、模版、附件。其中freemarker模板文件xxx.ftl放在resources文件夹下中template(通过FreemakrerConfig获取xxx.ftl的Template对象,然后转换为String),其中附件flcl.jpg放在resources文件夹中的static中(通过ResourceUtils获取文件对象File)。属性添加完成后,就可以发送了。

然后在controller或者其他service层中调用该方法就可以了。

补充:

message.ftl文件内容如下

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Hello</title>
  6. </head>
  7. <body>
  8. <h1>Send email</h1>
  9. <div>this email come from ${params}</div>
  10. </body>
  11. </html> 

发送成功后,可在收件箱中收到邮件

Spring Boot学习笔记:JavaMailSender发送邮件的更多相关文章

  1. Spring Boot学习笔记2——基本使用之最佳实践[z]

    前言 在上一篇文章Spring Boot 学习笔记1——初体验之3分钟启动你的Web应用已经对Spring Boot的基本体系与基本使用进行了学习,本文主要目的是更加进一步的来说明对于Spring B ...

  2. Spring Boot中使用JavaMailSender发送邮件

    相信使用过Spring的众多开发者都知道Spring提供了非常好用的JavaMailSender接口实现邮件发送.在Spring Boot的Starter模块中也为此提供了自动化配置.下面通过实例看看 ...

  3. Spring Boot 学习笔记(六) 整合 RESTful 参数传递

    Spring Boot 学习笔记 源码地址 Spring Boot 学习笔记(一) hello world Spring Boot 学习笔记(二) 整合 log4j2 Spring Boot 学习笔记 ...

  4. Spring Boot 学习笔记1——初体验之3分钟启动你的Web应用[z]

    前言 早在去年就简单的使用了一下Spring Boot,当时就被其便捷的功能所震惊.但是那是也没有深入的研究,随着其在业界被应用的越来越广泛,因此决定好好地深入学习一下,将自己的学习心得在此记录,本文 ...

  5. Spring Boot 学习笔记1---初体验之3分钟启动你的Web应用

    前言 早在去年就简单的使用了一下Spring Boot,当时就被其便捷的功能所震惊.但是那是也没有深入的研究,随着其在业界被应用的越来越广泛,因此决定好好地深入学习一下,将自己的学习心得在此记录,本文 ...

  6. Spring Boot 学习笔记--整合Thymeleaf

    1.新建Spring Boot项目 添加spring-boot-starter-thymeleaf依赖 <dependency> <groupId>org.springfram ...

  7. 我的第一个spring boot程序(spring boot 学习笔记之二)

    第一个spring boot程序 写在前面:鉴于spring注解以及springMVC的配置有大量细节和知识点,在学习理解之后,我们将直接进入spring boot的学习,在后续学习中用到注解及其他相 ...

  8. Java框架spring Boot学习笔记(六):Spring Boot事务管理

    SpringBoot和Java框架spring 学习笔记(十九):事务管理(注解管理)所讲的类似,使用@Transactional注解便可以轻松实现事务管理.

  9. Spring Boot学习笔记---Spring Boot 基础及使用idea搭建项目

    最近一段时间一直在学习Spring Boot,刚进的一家公司也正好有用到这个技术.虽然一直在学习,但是还没有好好的总结,今天周末先简单总结一下基础知识,等有时间再慢慢学习总结吧. Spring Boo ...

随机推荐

  1. selenium ide界面介绍

    Selenium Ide是firefox浏览器的一个插件,可以进行web的录制和回放,完成简单的自动化测试,同时可以将录制的脚本导出多种语言的脚本. 下面是Selenium Ide的界面: Base  ...

  2. Android Studio 插件-Android Styler 的使用 (转)

    作用:把 xml文件 转为 style 截图保留 使用方法 使用方法:选中xml代码 按下 Ctrl+Shift+D 转自:http://blog.csdn.net/zxwd2015/article/ ...

  3. pyinstaller linux系统下打包python源文件

    将python程序放在其他linux服务器中执行,通常linux服务器中默认安装python2.6,很多情况下需要升级为2.7  且要安装程序中需要的第三方模块,配置较为麻烦,所以通过在本地linux ...

  4. Redis集群架构【转载】

    Redis 集群的 TCP 端口(Redis Cluster TCP ports) 每个 Redis 集群节点需要两个 TCP 连接打开.正常的 TCP 端口用来服务客户端,例如 6379,加 100 ...

  5. jenkin、SVN、archery集成openLDAP

    jenkins: 1.下载.安装插件 LDAP .Matrix Authorization Strategy 2. 系统管理 —> 全局安全配置 点击 启用安全,并且选择 LDAP 认证,这里有 ...

  6. 使用phpStudy运行伊人集项目

    1.首次运行时,需要把system/config/install.look.php以及system/config/database.php(后面这个文件可以先不删除,若是安装过程中数据库报错,再来删除 ...

  7. Genymotion 模拟器上网出现 net::ERR_NAME_NOT_RESOLVED

    Genymotion 模拟器在公司网络安装的,然后启动能正常上网,把笔记本带回家,网络变化了,再使用模拟器 上网显示: (net::ERR_NAME_NOT_RESOLVED) 各种百度,最后用如下方 ...

  8. 官方教程:Apache Kylin和Superset集成,使用开源组件,完美打造OLAP系统

    本文转自Apache Kylin公众号apachekylin. Superset 是一个数据探索和可视化平台,设计用来提供直观的,可视化的,交互式的分析体验. Superset 提供了两种分析数据源的 ...

  9. position的absolute与fixed,absolute与relative共同点与不同点

    absolute与fixed 共同点: (1) 改变行内元素的呈现方式,display被置为block: (2) 让元素脱离普通流,不占据空间: (3) 默认会覆盖到非定位元素上 不同点: absol ...

  10. XP下1433端口打不开

    问题:操作系统windows xp:数据库sql server 2000:安装后通过程序无法访问数据,原因是数据库的默认端口1433未打开. 原因:sql server 2000的bug,需要升级补丁 ...