使用SpringBoot发送mail邮件
1、前言
发送邮件应该是网站的必备拓展功能之一,注册验证,忘记密码或者是给用户发送营销信息。正常我们会用JavaMail相关api来写发送邮件的相关代码,但现在springboot提供了一套更简易使用的封装。
2、Mail依赖
-
<dependency>
-
<groupId>org.springframework.boot</groupId>
-
<artifactId>spring-boot-starter-mail</artifactId>
-
<version>${spring-boot-mail.version}</version>
-
</dependency>
来看看其依赖树:
可以看到spring-boot-starter-mail-xxx.jar对Sun公司的邮件api功能进行了相应的封装。
3、Mail自动配置类: MailSenderAutoConfiguration
其实肯定可以猜到Spring Boot对Mail功能已经配置了相关的基本配置信息,它是Spring Boot官方提供,其类为MailSenderAutoConfiguration:
-
//MailSenderAutoConfiguration
-
@Configuration
-
@ConditionalOnClass({ MimeMessage.class, MimeType.class })
-
@ConditionalOnMissingBean(MailSender.class)
-
@Conditional(MailSenderCondition.class)
-
@EnableConfigurationProperties(MailProperties.class)
-
@Import(JndiSessionConfiguration.class)
-
public class MailSenderAutoConfiguration {
-
-
private final MailProperties properties;
-
-
private final Session session;
-
-
public MailSenderAutoConfiguration(MailProperties properties,
-
ObjectProvider<Session> session) {
-
this.properties = properties;
-
this.session = session.getIfAvailable();
-
}
-
-
@Bean
-
public JavaMailSenderImpl mailSender() {
-
JavaMailSenderImpl sender = new JavaMailSenderImpl();
-
if (this.session != null) {
-
sender.setSession(this.session);
-
}
-
else {
-
applyProperties(sender);
-
}
-
return sender;
-
}
-
-
//other code...
-
}
首先,它会通过注入Mail的属性配置类MailProperties:
-
@ConfigurationProperties(prefix = "spring.mail")
-
public class MailProperties {
-
-
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
-
-
/**
-
* SMTP server host.
-
*/
-
private String host;
-
-
/**
-
* SMTP server port.
-
*/
-
private Integer port;
-
-
/**
-
* Login user of the SMTP server.
-
*/
-
private String username;
-
-
/**
-
* Login password of the SMTP server.
-
*/
-
private String password;
-
-
/**
-
* Protocol used by the SMTP server.
-
*/
-
private String protocol = "smtp";
-
-
/**
-
* Default MimeMessage encoding.
-
*/
-
private Charset defaultEncoding = DEFAULT_CHARSET;
-
-
/**
-
* Additional JavaMail session properties.
-
*/
-
private Map<String, String> properties = new HashMap<String, String>();
-
-
/**
-
* Session JNDI name. When set, takes precedence to others mail settings.
-
*/
-
private String jndiName;
-
-
/**
-
* Test that the mail server is available on startup.
-
*/
-
private boolean testConnection;
-
-
//other code...
-
-
}
在MailSenderAutoConfiguration自动配置类中,创建了一个Bean,其类为JavaMailSenderImpl,它是Spring专门用来发送Mail邮件的服务类,SpringBoot也使用它来发送邮件。它是JavaMailSender接口的实现类,通过它的send()方法来发送不同类型的邮件,主要分为两类,一类是简单的文本邮件,不带任何html格式,不带附件,不带图片等简单邮件,还有一类则是带有html格式文本或者链接,有附件或者图片的复杂邮件。
4、发送邮件
通用配置application.properties:
-
# 设置邮箱主机
-
spring.mail.host=smtp.qq.com
-
-
# 设置用户名
-
spring.mail.username=xxxxxx@qq.com
-
-
# 设置密码,该处的密码是QQ邮箱开启SMTP的授权码而非QQ密码
-
spring.mail.password=pwvtabrwxogxidac
-
-
# 设置是否需要认证,如果为true,那么用户名和密码就必须的,
-
# 如果设置false,可以不设置用户名和密码,当然也得看你的对接的平台是否支持无密码进行访问的。
-
spring.mail.properties.mail.smtp.auth=true
-
-
# STARTTLS[1] 是对纯文本通信协议的扩展。它提供一种方式将纯文本连接升级为加密连接(TLS或SSL),而不是另外使用一个端口作加密通信。
-
spring.mail.properties.mail.smtp.starttls.enable=true
-
spring.mail.properties.mail.smtp.starttls.required=true
-
-
mail.from=${spring.mail.username}
-
mail.to=yyyyyy@qq.com
由于使用QQ邮箱的用户占多数,所以这里选择QQ邮箱作为测试。还有注意的是spring.mail.password这个值不是QQ邮箱的密码,而是QQ邮箱给第三方客户端邮箱生成的授权码。具体要登录QQ邮箱,点击设置,找到SMTP服务:
默认SMTP服务是关闭的,即默认状态为关闭状态,如果是第一次操作,点击开启后,会通过验证会获取到授权码;而我之前已经开启过SMTP服务,所以直接点击生成授权码后通过验证获取到授权码。
自定义的MailProperties配置类,用于解析mail开头的配置属性:
-
@Component
-
@ConfigurationProperties(prefix = "mail")
-
public class MailProperties {
-
-
private String from;
-
-
private String to;
-
-
//getter and setter...
-
}
4.1、测试发送简单文本邮件
-
@SpringBootTest
-
@RunWith(SpringJUnit4ClassRunner.class)
-
public class SimpleMailTest {
-
-
@Autowired
-
private MailService mailService;
-
-
@Test
-
public void sendMail(){
-
-
mailService.sendSimpleMail("测试Springboot发送邮件", "发送邮件...");
-
}
-
}
sendSimpleMail():
-
@Override
-
public void sendSimpleMail(String subject, String text) {
-
SimpleMailMessage mailMessage = new SimpleMailMessage();
-
mailMessage.setFrom(mailProperties.getFrom());
-
mailMessage.setTo(mailProperties.getTo());
-
-
mailMessage.setSubject(subject);
-
mailMessage.setText(text);
-
-
javaMailSender.send(mailMessage);
-
}
观察结果:
4.2、测试发送带有链接和附件的复杂邮件
事先准备一个文件file.txt,放在resources/public/目录下。
-
@SpringBootTest
-
@RunWith(SpringJUnit4ClassRunner.class)
-
public class MimeMailTest {
-
-
@Autowired
-
private MailService mailService;
-
-
@Test
-
public void testMail() throws MessagingException {
-
-
Map<String, String> attachmentMap = new HashMap<>();
-
attachmentMap.put("附件", "file.txt的绝对路径");
-
-
mailService.sendHtmlMail("测试Springboot发送带附件的邮件", "欢迎进入<a href=\"http://www.baidu.com\">百度首页</a>", attachmentMap);
-
-
}
-
}
sendHtmlMail():
-
@Override
-
public void sendHtmlMail(String subject, String text, Map<String, String> attachmentMap) throws MessagingException {
-
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
-
-
//是否发送的邮件是富文本(附件,图片,html等)
-
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
-
-
messageHelper.setFrom(mailProperties.getFrom());
-
messageHelper.setTo(mailProperties.getTo());
-
-
messageHelper.setSubject(subject);
-
messageHelper.setText(text, true);//重点,默认为false,显示原始html代码,无效果
-
-
if(attachmentMap != null){
-
attachmentMap.entrySet().stream().forEach(entrySet -> {
-
try {
-
File file = new File(entrySet.getValue());
-
if(file.exists()){
-
messageHelper.addAttachment(entrySet.getKey(), new FileSystemResource(file));
-
}
-
} catch (MessagingException e) {
-
e.printStackTrace();
-
}
-
});
-
}
-
-
javaMailSender.send(mimeMessage);
-
}
观察结果:
4.3、测试发送模版邮件
这里使用Freemarker作为模版引擎。
-
<dependency>
-
<groupId>org.springframework.boot</groupId>
-
<artifactId>spring-boot-starter-freemarker</artifactId>
-
<version>${spring-boot-freemarker.version}</version>
-
</dependency>
事先准备一个模版文件mail.ftl
-
<html>
-
<body>
-
<h3>你好, <span style="color: red;">${username}</span>, 这是一封模板邮件!</h3>
-
</body>
-
</html>
模版测试类:
-
@SpringBootTest
-
@RunWith(SpringJUnit4ClassRunner.class)
-
public class MailTemplateTest {
-
-
@Autowired
-
private MailService mailService;
-
-
@Test
-
public void testFreemarkerMail() throws MessagingException, IOException, TemplateException {
-
-
Map<String, Object> params = new HashMap<>();
-
params.put("username", "Cay");
-
-
mailService.sendTemplateMail("测试Springboot发送模版邮件", params);
-
-
}
-
}
sendTemplateMail():
-
@Override
-
public void sendTemplateMail(String subject, Map<String, Object> params) throws MessagingException, IOException, TemplateException {
-
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
-
-
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
-
-
helper.setFrom(mailProperties.getFrom());
-
helper.setTo(mailProperties.getTo());
-
-
Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
-
configuration.setClassForTemplateLoading(this.getClass(), "/templates");
-
-
String html = FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate("mail.ftl"), params);
-
-
helper.setSubject(subject);
-
helper.setText(html, true);//重点,默认为false,显示原始html代码,无效果
-
-
javaMailSender.send(mimeMessage);
-
}
观察结果:
原文地址:https://blog.csdn.net/caychen/article/details/82887926
使用SpringBoot发送mail邮件的更多相关文章
- SpringBoot 发送简单邮件
使用SpringBoot 发送简单邮件 1. 在pom.xml中导入依赖 <!--邮件依赖--> <dependency> <groupId>org.springf ...
- springboot发送email邮件
添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>sp ...
- SpringBoot整合Mail发送邮件&发送模板邮件
整合mail发送邮件,其实就是通过代码来操作发送邮件的步骤,编辑收件人.邮件内容.邮件附件等等.通过邮件可以拓展出短信验证码.消息通知等业务. 一.pom文件引入依赖 <dependency&g ...
- springboot集成mail实现邮件服务
1,新建mailconfig类,对邮件服务固定配置进行实体封装: import java.util.Properties; import org.springframework.beans.facto ...
- Springboot+Javamail实现邮件发送
Springboot+Javamail实现邮件发送 使用的是spring-context-support-5.2.6.RELEASE.jar里的javamail javamail 官方文档:javam ...
- SpringBoot实现QQ邮件发送
建项目 创建一个SpringBoot项目 改pom,导入相关依赖 org.springframework.boot spring-boot-starter-parent 2.2.2.RELEASE & ...
- .Net Mail SMTP 发送网络邮件
刚刚迈入"开发"的行列 一直有一个想法 我什么时候能给我庞大的用户信息数据库给每一位用户邮箱发送推荐信息呢? 刚迈入"编程两个月的时间" 我采用 SMTP 发送 ...
- Linux mail 邮件发送
Linux mail 邮件介绍 在Linux系统下我们可以通过”mail“命令,发送邮件,在运维中通常我们它来实现邮件告警. 安装 (方案1) 一.安装邮件服务 yum install -y send ...
- Java Mail 邮件发送简单封装
上一篇文章我们用写了一个Java Mail 的Demo,相信你已经可以用那个例子来发送邮件了.但是Demo 有很多的问题. 首先每次发送需要配置的东西很多,包括发件人的邮箱和密码.smtp服务器和SM ...
随机推荐
- ThinkPHP 删除数据
ThinkPHP删除数据使用delete方法,例如: 直线电机价格 $Form = M('Form'); $Form->delete(5); 表示删除主键为5的数据,delete方法可以删除单个 ...
- B/S架构及其运行原理
一. B/S的概念 B/S(Brower/Server,浏览器/服务器)模式又称B/S结构,是Web兴起后的一种网络结构模式.Web浏览器是客户端最主要的应用软件. 这种模式统一了客户端,将系统功能实 ...
- 菜鸟nginx源码剖析数据结构篇(六) 哈希表 ngx_hash_t(上)[转]
菜鸟nginx源码剖析数据结构篇(六) 哈希表 ngx_hash_t(上) Author:Echo Chen(陈斌) Email:chenb19870707@gmail.com Blog:Blog.c ...
- Spring MVC(七)--传递JSON参数
有时候参数的传递还需要更多的参数,比如一个获取用户信息的请求中既有用户ID等基本参数,还要求对查询结果进行分页,针对这种场景,一般都会将分页参数封装成一个对象,然后将它和基本参数一起传给控制器,为了控 ...
- PAT甲级——A1089 Insert or Merge
According to Wikipedia: Insertion sort iterates, consuming one input element each repetition, and gr ...
- 5行代码怎么实现Hadoop的WordCount?
初学编程的人,都知道hello world的含义,当你第一次从控制台里打印出了hello world,就意味着,你已经开始步入了编程的大千世界,这和第一个吃螃蟹的人的意义有点类似,虽然这样比喻并不恰当 ...
- SPRINGBOOT配置MYSQL,MYBATIS,DRUID
配置 DRUID连接池 MYSQL数据库 MYBATIS持久层框架 添加依赖 <dependency> <groupId>mysql</groupId> <a ...
- NtQuerySystemInformation 枚举进程
函数原型: NTSTATUS WINAPI NtQuerySystemInformation( _In_ SYSTEM_INFORMATION_CLASS SystemInformat ...
- 02.Hibernate配置文件之映射配置文件
映射文件,即xxx.hbm.xml的配置文件 <class>标签:用来将类与数据库表建立映射关系 属性: name:类中的全路径 table:表名(如果类与表名一致,那么table属性可以 ...
- Odoo文档管理/知识管理应用实践 - 上传附件
测试环境: Odoo8.0 Odoo中的文档管理/知识管理可用于保存采购.销售.生产等一系列业务流程中产生的文件.凭证,可关联到具体的每一笔业务操作:也能用于管理公司的合同.资料,创建知识库以分享内部 ...