1、前言
邮件发送功能非常普遍,用户注册验证、重要通知、调查问卷等都会用到邮件发送。
而Spring-boot进一步简化了Java邮件配置,一个简单邮件(不含附件)发送的核心代码仅为7行,非常适合新手入门。
2、前期准备
1、本文全程使用163邮箱作为发件邮箱,需要开启邮箱的POP3/SMTP服务。
2、本文将从以下三个方面进行讲解:
①发送简单邮件(不含附件)
②发送带附件的邮件(进阶)
③使用Thymeleaf模板构建邮件模板发送邮件(进阶,了解即可)
3、发送简单邮件
1、创建一个demomail项目,勾选 Spring Web和Java Mail Sender依赖。项目依赖均在pom.xml集中管理,后续可以增加/修改。
2、我们在src-->main-->java-->com.example.demomail下创建一个package(文件夹),命名为Service,再创建一个package,命名为Controller。
我们又分别在Service下面创建一个MailService类,在Controller下面创建一个MailController类,项目结构树如下图。
3、在application.properties中进行邮件基本信息的配置。Spring-boot最核心的就是使用配置从而简化操作。
我们将下方配置文件复制到application.properties中。将发件邮箱修改为你个人163邮箱的配置。
#重新定义一个服务端口,默认是8080
server.port=8081
#邮箱基本信息配置--------------------------------------
#发件服务器地址
spring.mail.host=smtp.163.com
#发件服务器端口,163邮箱为465
spring.mail.port=465
#发件箱账号,我的发件邮箱为lulc@163.com
spring.mail.username=lulc(需要修改)
#发件箱密码,163邮箱为发件邮箱密码,QQ邮箱为申请的授权码
spring.mail.password=***1984***(需要修改)
#邮箱编码设置
spring.mail.default-encoding=utf-8
#SSL连接配置
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
#后台是否打开DEBUG模式,测试可以打开,正式应用改为false
spring.mail.properties.mail.debug=true
#邮箱基本信息配置完毕--------------------------------------
4、接下来我们完成MailService核心代码,JavaMailSender是Spring-boot在MailSenderPropertiesConfiguration类中配置好的,该类在Mail自动配置类MailSenderAutoConfiguration中导入,因此这里直接通过@Autowired注入JavaMailSender就可以使用了。
SendSimpleMail方法的5个参数分别表示邮件发送者、收件人、抄送人、邮件主题和邮件内容。
package com.example.demomail.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
@Component
public class MailService {
@Autowired
JavaMailSender sender;//直接注入JavaMailSender
public void sendmail(String from, String to, String cc, String subject, String content) {
SimpleMailMessage mail = new SimpleMailMessage();
mail.setFrom(from);//发送者
mail.setTo(to);//收件人
mail.setCc(cc);//抄送人
mail.setSubject(subject);//邮件主题
mail.setText(content);//邮件内容
sender.send(mail);//发送邮件
}
}
5、最后我们完善一下MailController,就可以进行测试了。
package com.example.demomail.Controller;
import com.example.demomail.Service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MailController {
@Autowired
MailService service;//注入刚才写好的MailService
@GetMapping("/mail")//等同于@RequestMapping(method = RequestMethod.GET)
public String sendmail(){
service.sendmail("lulc@163.com","182305213@qq.com","lulc@163.com",
"会议通知","请于下午三点在1号会议室参加民主生活会");
return "邮件发送成功!";
}
}
6、右键DemomailApplication,点击Run DemomailApplication,运行程序。打开浏览器输入网址:http://localhost:8081/mail
网页显示:邮件发送成功!IDE也会有成功提示,QQ邮箱也收到了会议通知的邮件。
当你第一次使用代码发送邮件并成功收到了邮件提示,是不是很激动!
4、发送带附件的邮件(进阶)
1、要发送一个带附件的邮件也非常容易,我们使用MimeMessageHelper简化邮件配置,它的构造方法的第二个参数true表示构造一个multipart类型的邮件,即包含多个正文、附件、内嵌资源,表现形式更加丰富。最后通过addAttachment方法添加附件。
我们在MailService中继续添加代码,这里我们以多附件为例。
package com.example.demomail.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Component
public class MailService {
@Autowired
JavaMailSender sender;//直接注入JavaMailSender
//发送简单邮件
public void sendmail(String from, String to, String cc, String subject, String content) {
SimpleMailMessage mail = new SimpleMailMessage();
mail.setFrom(from);//发送者
mail.setTo(to);//收件人
mail.setCc(cc);//抄送人
mail.setSubject(subject);//邮件主题
mail.setText(content);//邮件内容
sender.send(mail);//发送邮件
}
//发送带多附件的邮件 File[] files表示附件集
public void sendfilemail(String from, String to, String cc, String subject, String content, File[] files) {
try {
MimeMessage mimeMessage = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);//第二个参数true
helper.setFrom(from);
helper.setTo(to);
helper.setCc(cc);
helper.setSubject(subject);
helper.setText(content);
//循环添加多附件
for (int i = 0; i < files.length; i++) {
helper.addAttachment(files[i].getName(), files[i]);
}
sender.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
2、我们在MailController中继续添加代码,就可以测试了。
package com.example.demomail.Controller;
import com.example.demomail.Service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
@RestController
public class MailController {
@Autowired
MailService service;//注入刚才写好的MailService
//简单邮件
@GetMapping("/mail")//等同于@RequestMapping(method = RequestMethod.GET)
public String sendmail(){
service.sendmail("lulc@163.com","182305213@qq.com","lulc@163.com",
"会议通知","请于下午三点在1号会议室参加民主生活会");
return "邮件发送成功!";
}
//多附件有邮件
@GetMapping("/mailfile")
public String sendfilemail(){
File[] files =new File[2];//表明有两个附件
files[0] =new File("D:\\会议内容.docx");//附件分别存放在D盘根目录
files[1] =new File("D:\\会议议程.xlsx");
service.sendfilemail("lulc@163.com","182305213@qq.com","lulc@163.com",
"会议通知","请于下午三点在1号会议室参加民主生活会,详见附件",files);
return"带附件邮件发送成功!";
}
}
3、右键DemomailApplication,点击Run DemomailApplication,运行程序。打开浏览器输入网址:http://localhost:8081/mailfile
带附件邮件发送成功!
5、使用Thymeleaf模板构建邮件模板发送邮件(进阶,了解即可)
1、对于复杂样式邮件,如果采用HTML字符串拼接的方式,不但容易出错,且不易于维护,而使用HTML模板可以很好的解决这一问题。这里我们采用Thymeleaf作为邮件构建的模板,首先添加Thymeleaf依赖,参考3.1介绍。
其次创建相应的的邮件模板mailtemplate.html,Thymeleaf模板默认位置是在resource/templates目录下。
我们以邮箱激活为场景,mailtemplate.html代码如下:
其中用户名${username}和性别${gender}为动态赋值。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>thymeleaf邮件</title>
</head>
<body>
<div>邮箱激活</div>
<div>您的注册信息是
<table border="1">
<tr>
<td>用户名</td>
<td th:text="${username}"></td>
</tr>
<tr>
<td>性别</td>
<td th:text="${gender}"></td>
</tr>
</table>
</div>
<div>
<a href="http://www.baidu.com">核对无误请点击本链接激活</a>
</div>
</body>
</html>
2、我们在MailService中继续添加代码,和发送多附件邮件的代码基本一致。
package com.example.demomail.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Component
public class MailService {
@Autowired
JavaMailSender sender;//直接注入JavaMailSender
//发送简单邮件
public void sendmail(String from, String to, String cc, String subject, String content) {
SimpleMailMessage mail = new SimpleMailMessage();
mail.setFrom(from);//发送者
mail.setTo(to);//收件人
mail.setCc(cc);//抄送人
mail.setSubject(subject);//邮件主题
mail.setText(content);//邮件内容
sender.send(mail);//发送邮件
}
//发送带多附件的邮件 File[] files表示附件集
public void sendfilemail(String from, String to, String cc, String subject, String content, File[] files) {
try {
MimeMessage mimeMessage = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);//第二个参数true
helper.setFrom(from);
helper.setTo(to);
helper.setCc(cc);
helper.setSubject(subject);
helper.setText(content);
//循环添加多附件
for (int i = 0; i < files.length; i++) {
helper.addAttachment(files[i].getName(), files[i]);
}
sender.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}
//thymeleaf作为模板发邮件
public void sendthymeleafmail(String from, String to, String cc, String subject, String content,File[] files) {
try {
MimeMessage mail2 = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mail2 , true);
helper.setFrom(from);
helper.setTo(to);
helper.setCc(cc);
helper.setSubject(subject);
helper.setText(content,true);
//多附件
for (int i = 0; i < files.length; i++) {
helper.addAttachment(files[i].getName(), files[i]);
}
sender.send(mail2);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
3、我们在MailController中继续添加代码,就可以测试了。
Thymeleaf提供了TemplateEngine来对模板进行渲染,将HTML转化为Content邮件内容,此时需要注入TemplateEngin,将HTML转化为htmlcontent。
动态赋值我们通过Context构造模板中变量需要的值。
package com.example.demomail.Controller;
import com.example.demomail.Service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import java.io.File;
@RestController
public class MailController {
@Autowired
MailService service;//注入刚才写好的MailService
//简单邮件
@GetMapping("/mail")//等同于@RequestMapping(method = RequestMethod.GET)
public String sendmail(){
service.sendmail("lulc@163.com","182305213@qq.com","lulc@163.com",
"会议通知","请于下午三点在1号会议室参加民主生活会");
return "邮件发送成功!";
}
//多附件有邮件
@GetMapping("/mailfile")
public String sendfilemail(){
File[] files =new File[2];//表明有两个附件
files[0] =new File("D:\\会议内容.docx");//附件分别存放在D盘根目录
files[1] =new File("D:\\会议议程.xlsx");
service.sendfilemail("lulc@163.com","182305213@qq.com","lulc@163.com",
"会议通知","请于下午三点在1号会议室参加民主生活会,详见附件",files);
return"带附件邮件发送成功!";
}
//thymeleaf模板作为正文的邮件
@Autowired
TemplateEngine templateEngine;//注入TemplateEngine对网页模板进行渲染
@GetMapping("/mailthy")
public String sendthymail(){
Context context =new Context();
context.setVariable("username","路路");
context.setVariable("gender","男");
String htmlcontent =templateEngine.process("mailtemplate.html",context);
File[] files =new File[2];//表明有两个附件
files[0] =new File("D:\\内容预览.docx");//附件分别存放在D盘根目录
files[1] =new File("D:\\使用手册.xlsx");
service.sendthymeleafmail("lulc@163.com","182305213@qq.com","lulc@163.com",
"邮箱激活通知",htmlcontent,files);
return"Thymeleaf邮件发送成功!";
}
}
4、右键DemomailApplication,点击Run DemomailApplication,运行程序。打开浏览器输入网址开始测试:http://localhost:8081/mailthy
Thymeleaf邮件发送成功!并将"username","路路","gender","男"动态赋值到邮件内容中。
6、总结
以上三种邮件发送方式基本上能满足大部分的业务需求,后续可以根据实际需求自行部署邮件发送服务,可使用网页、微信小程序、各式APP作为前端调用邮件发送服务,也可将其作为接口,供其他生产系统访问调用,并最终完成邮件发送业务。
最后补充一点:批量单用户发送邮件只需要循环收件人地址,调用邮件发送服务即可。
好了,本讲到此结束,后续我将陆续更新一些如何利用Spring-boot搭建生产级应用的案例,欢迎关注、留言、转发。