springboot发送邮件
Spring提供了非常好用的JavaMailSender
接口实现邮件发送。在Spring Boot的Starter模块中也为此提供了自动化配置。下面通过实例看看如何在Spring Boot中使用JavaMailSender
发送邮件。
快速入门:
那么如何进行使用呢?很简单最核心的就两个步骤:
在Spring Boot的工程中的pom.xml
中引入spring-boot-starter-mail
依赖:
<!-- 发送邮件. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
如其他自动化配置模块一样,在完成了依赖引入之后,只需要在application.properties
中配置相应的属性内容。
下面我们以QQ邮箱为例,在application.properties
中加入如下配置(注意替换自己的用户名和密码):
########################################################
###mail setting
########################################################
# 设置邮箱主机
spring.mail.host=smtp.qq.com
# 设置用户名
spring.mail.username=用户名
# 设置密码
spring.mail.password=密码
# 设置是否需要认证,如果为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
接下来我们通过单元测试来测试简单邮件的发送:
(如何在spring boot进行单元测试可以参看文章:
http://412887952-qq-com.iteye.com/blog/2292739
)
package com.kfit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
*
* @author Angel(QQ:412887952)
* @version v.0.1
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = App.class)
public class AppTest {
@Autowired
private JavaMailSender mailSender;
/**
* 修改application.properties的用户,才能发送。
*/
@Test
public void sendSimpleEmail(){
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("412887952@qq.com");//发送者.
message.setTo("1473773560@qq.com");//接收者.
message.setSubject("测试邮件(邮件主题)");//邮件主题.
message.setText("这是邮件内容");//邮件内容.
mailSender.send(message);//发送邮件
}
}
一个简单的邮件发送就完成了,运行一下该单元测试,看看效果如何?
由于Spring Boot的starter模块提供了自动化配置,所以在引入了spring-boot-starter-mail
依赖之后,会根据配置文件中的内容去创建JavaMailSender
实例,因此我们可以直接在需要使用的地方直接@Autowired
来引入邮件发送对象。
进阶使用:
我们通过使用SimpleMailMessage
实现了简单的邮件发送,但是实际使用过程中,我们还可能会带上附件、或是使用邮件模块等。这个时候我们就需要使用MimeMessage
来设置复杂一些的邮件内容,下面我们就来依次实现一下。
发送附件
发送附件主要通过MimeMessageHelper来进行操作的,实际中也很简单。
/**
* 测试发送附件.(这里发送图片.)
* @throws MessagingException
*/
@Test
public void sendAttachmentsEmail() throws MessagingException{
//这个是javax.mail.internet.MimeMessage下的,不要搞错了。
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//基本设置.
helper.setFrom("412887952@qq.com");//发送者.
helper.setTo("1473773560@qq.com");//接收者.
helper.setSubject("测试附件(邮件主题)");//邮件主题.
helper.setText("这是邮件内容(有附件哦.)");//邮件内容.
//org.springframework.core.io.FileSystemResource下的:
//附件1,获取文件对象.
FileSystemResource file1 = new FileSystemResource(new File("D:/test/head/head1.jpg"));
//添加附件,这里第一个参数是在邮件中显示的名称,也可以直接是head.jpg,但是一定要有文件后缀,不然就无法显示图片了。
helper.addAttachment("头像1.jpg", file1);
//附件2
FileSystemResource file2 = new FileSystemResource(new File("D:/test/head/head2.jpg"));
helper.addAttachment("头像2.jpg", file2);
mailSender.send(mimeMessage);
}
嵌入静态资源:
除了发送附件之外,我们在邮件内容中可能希望通过嵌入图片等静态资源,让邮件获得更好的阅读体验,而不是从附件中查看具体图片,下面的测试用例演示了如何通过MimeMessageHelper
实现在邮件正文中嵌入静态资源。
内嵌图片,给定一个CID值即可,增加附件,使用MimeMessageHelper的addAttachment即可现在一般不会做内嵌图片,因为这样邮件会很大,容易对服务器造成压力,一般做法是使用图片链接另外,如果要做内嵌或发送图片,你应该使用信用较高的邮箱帐户,否则会报错:554 DT:SPM 发送的邮件内容包含了未被许可的信息,或被系统识别为垃圾邮件。请检查是否有用户发送病毒或者垃圾邮件
对于163邮箱服务器会产生的其他问题,参见:http://help.163.com/09/1224/17/5RAJ4LMH00753VB8.html
以下是发送静态资源的核心代码:
/**
* 邮件中使用静态资源.
* @throws Exception
*/
@Test
public void sendInlineMail() throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//基本设置.
helper.setFrom("412887952@qq.com");//发送者.
helper.setTo("1473773560@qq.com");//接收者.
helper.setSubject("测试静态资源(邮件主题)");//邮件主题.
// 邮件内容,第二个参数指定发送的是HTML格式
//说明:嵌入图片<img src='cid:head'/>,其中cid:是固定的写法,而aaa是一个contentId。
helper.setText("<body>这是图片:<img src='cid:head' /></body>", true);
FileSystemResource file = new FileSystemResource(new File("D:/test/head/head1.jpg"));
helper.addInline("head",file);
mailSender.send(mimeMessage);
}
这里需要注意的是addInline
函数中资源名称head
需要与正文中cid:head
对应起来
嵌入图片<img src='cid:head'/>,其中cid:是固定的写法,而aaa是一个contentId。
模板邮件:
通常我们使用邮件发送服务的时候,都会有一些固定的场景,比如重置密码、注册确认等,给每个用户发送的内容可能只有小部分是变化的。所以,很多时候我们会使用模板引擎来为各类邮件设置成模板,这样我们只需要在发送时去替换变化部分的参数即可。
在Spring Boot中使用模板引擎来实现模板化的邮件发送也是非常容易的,下面我们以freemarker为例实现一下。
引入freemarker模块的依赖:
<!-- 引入模板引擎. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
加入配置信息:
########################################################
###FREEMARKER (FreeMarkerAutoConfiguration)
########################################################
spring.freemarker.allow-request-override=false
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
#spring.freemarker.prefix=
#spring.freemarker.request-context-attribute=
#spring.freemarker.settings.*=
#spring.freemarker.suffix=.ftl
#spring.freemarker.template-loader-path=classpath:/templates/ #comma-separated list
在resources/templates/
下,创建一个模板页面email.ftl
:
<html>
<body>
<h3>你好, ${username}, 这是一封模板邮件!</h3>
</body>
</html>
最后,我们在单元测试中加入发送模板邮件的测试用例,具体如下:
/**
* 模板邮件;
* @throws Exception
*/
@Test
public void sendTemplateMail() throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//基本设置.
helper.setFrom("412887952@qq.com");//发送者.
helper.setTo("1473773560@qq.com");//接收者.
helper.setSubject("模板邮件(邮件主题)");//邮件主题.
Map<String, Object> model = new HashMap<String, Object>();
model.put("username", "林峰");
Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
// 设定去哪里读取相应的ftl模板
cfg.setClassForTemplateLoading(this.getClass(), "/templates");
// 在模板文件目录中寻找名称为name的模板文件
Template template = cfg.getTemplate("email.ftl");
String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
helper.setText(html, true);
mailSender.send(mimeMessage);
}
运行一下,就可以收到内容为你好,
林峰
,
这是一封模板邮件
!
的邮件。这里,我们通过传入username的参数,在邮件内容中替换了模板中的${username}
变量。
springboot发送邮件相关推荐
- SpringBoot 发送邮件功能实现
背景 有个小伙伴问我你以前发邮件功能怎么弄的.然后我就给他找了个demo,正好在此也写一下,分享给大家. 理清痛点 发送邮件,大家可以想一下,坑的地方在哪? 我觉得是三个吧. 第一:邮件白名单问题. ...
- springboot发送邮件_SpringBoot发送邮件如何实现,SpringBoot发送邮件详解(附代码)...
在很多的项目开发中,总会遇到消息通知的场景,比如某个广告主提交一个表单,我们要通知提醒运营人员及时查看. 消息通知的形式也有很多,比如:短信.邮件.app推送等,本文主要给大家描述一下邮件通知的形式, ...
- SpringBoot发送邮件(二)发送包含图片的邮件
前言:使用发邮件这个功能不难,但是也有一些坑,下面我把开发邮件功能总结了一下分享给大家,同时为了避免篇幅过长,导致大家看的不仔细或看一半不想看了,我将这个功能细分了一下,写了好几篇供大家各取所需. S ...
- SpringBoot发送邮件通过SendGrid服务平台(带动态模板)
SpringBoot发送邮件通过SendGrid服务平台 一.开通API Keys 二.后台实现 一.开通API Keys 二.后台实现 加入maven依赖 <dependency>< ...
- [Springboot]发送邮件、重置密码业务实战
前言 忘记密码并通过邮件重置密码是一个常见的业务需求,在开发我的个人小项目过程中,也需要用到这个业务,今天就给大家带来一个业务实战. 开发环境 springboot:1.5.16.RELEASE 业务 ...
- springboot发送邮件-163邮箱
一.获取邮箱授权码 1.以163邮箱为例,页面首部找到设置,选择SMTP 2.开启POP3/SMTP服务 3.获取授权码 二.SpringBoot集成邮件发送 1.环境配置 添加依赖 <!-- ...
- SpringBoot发送邮件(网易邮箱,QQ邮箱,139邮箱)
添加依赖 <!-- 邮件服务 --> <dependency><groupId>org.springframework.boot</groupId>&l ...
- SpringBoot发送邮件(QQ邮箱、腾讯企业邮箱、网易邮箱、阿里云邮箱...)
目录 一.获取邮箱授权码 二.引入依赖 三.配置文件(请注意yml格式,或者使用.properties) 四.不带附件发邮箱 五.带附件发邮箱 六.邮箱类型拓展 本篇文章以QQ邮箱作为发件人写案例演示 ...
- Springboot发送邮件实现注册激活
在上一篇文章中,我们使用springboot整合邮件实现发送功能,那么下面来用邮件发送功能实现用户注册,方便我们进一步熟悉邮件发送功能的使用.实现步骤大致如下:进行用户注册同时发送一封激活邮件,邮件里 ...
- springboot发送邮件问题总结
欢迎大家关注我的公众号,添加我为好友! springboot内部集成了spring的邮件发送功能,所以在使用springboot进行邮件发送的时候需要在maven中加入以下依赖. <depend ...
最新文章
- Android设计模式MVVM之DataBinding简单使用
- Frida之安装和使用教程
- 2个红外传感器循迹原理_红外线光学气体浓度传感器作用原理
- Python应用实战-Clumper库 | 常用的数据操作函数
- 7年工作经验,面试官竟然让我写算法题?
- Python学习之路和隐藏特征
- JUNIPER SRX Ipsec ××× 点对点Policy base ×××连接测试
- vs2017python配置opencv_关于VS2017配置OpenCV出现无法打开文件“opencv_ml249d.lib”的解决方案...
- oracle查询当天数据三种方式性能对比
- python语言def_python中def的含义
- Windows远程连接Linux界面的两种方法
- adb命令 激活并设置默认输入法
- 百面机器学习2---模型评估
- nand flash基础时序
- 如何使用AE制作文字破碎动画?制作ae破碎文字特效教程分享
- 软件测试外包干了4年,感觉废了..
- Segger RTT深度使用说明-移植-Jlink rtt viewer显示-输出到Secure CRT
- 4.3.3 运行心跳任务
- android adb点击坐标,Android adb shell 获得点击屏幕的位置坐标
- 靶机18 driftingblues1