pom.xml 引入相关依赖
<!-- 发送邮件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<!--用于实现模板邮件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
如何获取三方登录授权码,自己百度去,实在不行使用邮箱登录密码也行
邮件的基本设置
spring:
#配置邮箱
mail:
host: 邮箱服务商的protocol服务器主机 #smtp.qq.com
port: 465
protocol: 邮件协议 #smtp
username: 指定邮箱服务商的邮箱账号 #7557*****@qq.com
nickname: 指定自定义发送人的昵称 #后台系统
password: 邮箱账号密码或者三方登录授权码 #jwgteykojlf*****
default-encoding: UTF-8
properties:
mail:
smtp:
socketFactory:
class: javax.net.ssl.SSLSocketFactory
debug: true #调试模式
test-connection: false #启动项目时验证是否可以正确通信 默认为false
发送邮件的Service接口
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
public interface MailService {
/**
* 发送文本
* @param subject 主题
* @param content 内容
* @param toWho 需要发送的人
* @param ccPeoples 需要抄送的人
* @param bccPeoples 需要密送的人
* @param attachments 需要附带的附件
*/
void sendSimpleTextMailActual(String subject,String content,String[] toWho,String[] ccPeoples,String[] bccPeoples,String[] attachments);
/**
* 发送Html
* @param subject 主题
* @param content 内容
* @param toWho 需要发送的人
*/
void sendHtmlMail(String subject,String content,String[] toWho);
/**
* 处理二进制邮件的基本信息,比如需要带附件的文本邮件、HTML文件、图片邮件、模板邮件等等
* @param mimeMessageHelper:二进制文件的包装类
* @param subject:邮件主题
* @param content:邮件内容
* @param toWho:收件人
* @param ccPeoples:抄送人
* @param bccPeoples:暗送人
* @param isHtml:是否是HTML文件,用于区分带附件的简单文本邮件和真正的HTML文件
* @return :返回这个过程中是否出现异常,当出现异常时会取消邮件的发送
*/
boolean handleBasicInfo(MimeMessageHelper mimeMessageHelper, String subject, String content, String[] toWho, String[] ccPeoples, String[] bccPeoples, boolean isHtml);
/**
* 用于填充简单文本邮件的基本信息
* @param simpleMailMessage:文本邮件信息对象
* @param subject:邮件主题
* @param content:邮件内容
* @param toWho:收件人
* @param ccPeoples:抄送人
* @param bccPeoples:暗送人
*/
void handleBasicInfo(SimpleMailMessage simpleMailMessage, String subject, String content, String[] toWho, String[] ccPeoples, String[] bccPeoples);
/**
* 发送html
* @param subject:邮件主题
* @param content:邮件内容
* @param toWho:收件人
* @param mimeMessageHelper:二进制文件的包装类
*/
void handleBasicInfo(MimeMessageHelper mimeMessageHelper,String subject, String content, String[] toWho);
/**
* 用于处理附件信息,附件需要 MimeMessage 对象
* @param mimeMessageHelper:处理附件的信息对象
* @param subject:邮件的主题,用于日志记录
* @param attachmentFilePaths:附件文件的路径,该路径要求可以定位到本机的一个资源
*/
void handleAttachment(MimeMessageHelper mimeMessageHelper,String subject,String[] attachmentFilePaths);
}
发送邮件的Service接口实现类(这里注意@Slf4j为日志的注解,如果没有依赖请自行导入或者删掉日志记录
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
/**
* 发送邮件功能具体实现类
* @author Xuan
* @date 2019/8/4 11:01
*/
@Service
@Slf4j
public class MailerServiceImpl implements MailService {
//默认编码
public static final String DEFAULT_ENCODING = "UTF-8";
//本身邮件的发送者,来自邮件配置
@Value("${spring.mail.username}")
private String userName;
@Value("${spring.mail.nickname}")
private String nickname;
//模板引擎解析对象,用于解析模板
@Autowired
private TemplateEngine templateEngine;
@Autowired(required = false)
private JavaMailSender mailSender;
@Override
public void sendSimpleTextMailActual(String subject,String content,String[] toWho,String[] ccPeoples,String[] bccPeoples,String[] attachments){
//检验参数:邮件主题、收件人、邮件内容必须不为空才能够保证基本的逻辑执行
if(subject == null||toWho == null||toWho.length == 0||content == null){
log.error("邮件-> {} 无法继续执行,因为缺少基本的参数:邮件主题、收件人、邮件内容",subject);
throw new RuntimeException("模板邮件无法继续发送,因为缺少必要的参数!");
}
log.info("开始发送简单文本邮件:主题->{},收件人->{},抄送人->{},密送人->{},附件->{}",subject,toWho,ccPeoples,bccPeoples,attachments);
//附件处理,需要处理附件时,需要使用二进制信息,使用 MimeMessage 类来进行处理
if(attachments != null&&attachments.length > 0){
try{
//附件处理需要进行二进制传输
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,DEFAULT_ENCODING);
//设置邮件的基本信息:这些函数都会在后面列出来
boolean continueProcess = handleBasicInfo(helper,subject,content,toWho,ccPeoples,bccPeoples,false);
//如果处理基本信息出现错误
if(!continueProcess){
log.error("邮件基本信息出错: 主题->{}",subject);
return;
}
//处理附件
handleAttachment(helper,subject,attachments);
//发送该邮件
mailSender.send(mimeMessage);
log.info("发送邮件成功: 主题->{}",subject);
} catch (MessagingException e) {
e.printStackTrace();
log.error("发送邮件失败: 主题->{}",subject);
}
}else{
//创建一个简单邮件信息对象
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
//设置邮件的基本信息
handleBasicInfo(simpleMailMessage,subject,content,toWho,ccPeoples,bccPeoples);
//发送邮件
mailSender.send(simpleMailMessage);
log.info("发送邮件成功: 主题->{}",subject,toWho,ccPeoples,bccPeoples,attachments);
}
}
@Override
public void sendHtmlMail(String subject, String content, String[] toWho) {
//检验参数:邮件主题、收件人、邮件内容必须不为空才能够保证基本的逻辑执行
if(subject == null||toWho == null||toWho.length == 0||content == null){
log.error("邮件-> {} 无法继续执行,因为缺少基本的参数:邮件主题、收件人、邮件内容",subject);
throw new RuntimeException("模板邮件无法继续发送,因为缺少必要的参数!");
}
log.info("开始发送Html邮件:主题->{},收件人->{}",subject,toWho);
//html
MimeMessage mimeMessage = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,DEFAULT_ENCODING);
//设置邮件的基本信息
handleBasicInfo(helper,subject,content,toWho);
//发送邮件
mailSender.send(mimeMessage);
log.info("html邮件发送成功");
} catch (MessagingException e) {
log.error("发送邮件出错->{}",subject);
}
log.info("发送邮件成功: 主题->{}",subject,toWho);
}
@Override
public boolean handleBasicInfo(MimeMessageHelper mimeMessageHelper,String subject,String content,String[] toWho,String[] ccPeoples,String[] bccPeoples,boolean isHtml){
try{
//设置必要的邮件元素
//设置发件人
mimeMessageHelper.setFrom(nickname+'<'+userName+'>');
//设置邮件的主题
mimeMessageHelper.setSubject(subject);
//设置邮件的内容,区别是否是HTML邮件
mimeMessageHelper.setText(content,isHtml);
//设置邮件的收件人
mimeMessageHelper.setTo(toWho);
//设置非必要的邮件元素,在使用helper进行封装时,这些数据都不能够为空
if(ccPeoples != null)
//设置邮件的抄送人:MimeMessageHelper # Assert.notNull(cc, "Cc address array must not be null");
mimeMessageHelper.setCc(ccPeoples);
if(bccPeoples != null)
//设置邮件的密送人:MimeMessageHelper # Assert.notNull(bcc, "Bcc address array must not be null");
mimeMessageHelper.setBcc(bccPeoples);
return true;
}catch(MessagingException e){
e.printStackTrace();
log.error("邮件基本信息出错->{}",subject);
}
return false;
}
@Override
public void handleBasicInfo(SimpleMailMessage simpleMailMessage,String subject,String content,String[] toWho,String[] ccPeoples,String[] bccPeoples){
//设置发件人
simpleMailMessage.setFrom(nickname+'<'+userName+'>');
//设置邮件的主题
simpleMailMessage.setSubject(subject);
//设置邮件的内容
simpleMailMessage.setText(content);
//设置邮件的收件人
simpleMailMessage.setTo(toWho);
//设置邮件的抄送人
simpleMailMessage.setCc(ccPeoples);
//设置邮件的密送人
simpleMailMessage.setBcc(bccPeoples);
}
@Override
public void handleBasicInfo(MimeMessageHelper mimeMessageHelper,String subject,String content,String[] toWho){
try {
//设置发件人
mimeMessageHelper.setFrom(nickname+'<'+userName+'>');
//设置邮件的主题
mimeMessageHelper.setSubject(subject);
//设置邮件的内容
mimeMessageHelper.setText(content,true);
//设置邮件的收件人
mimeMessageHelper.setTo(toWho);
} catch (MessagingException e) {
log.error("html邮件基本信息出错->{}",subject);
}
}
@Override
public void handleAttachment(MimeMessageHelper mimeMessageHelper,String subject,String[] attachmentFilePaths){
//判断是否需要处理邮件的附件
if(attachmentFilePaths != null&&attachmentFilePaths.length > 0) {
FileSystemResource resource;
String fileName;
//循环处理邮件的附件
for (String attachmentFilePath : attachmentFilePaths) {
//获取该路径所对应的文件资源对象
resource = new FileSystemResource(new File(attachmentFilePath));
//判断该资源是否存在,当不存在时仅仅会打印一条警告日志,不会中断处理程序。
// 也就是说在附件出现异常的情况下,邮件是可以正常发送的,所以请确定你发送的邮件附件在本机存在
if (!resource.exists()) {
log.warn("邮件->{} 的附件->{} 不存在!", subject, attachmentFilePath);
//开启下一个资源的处理
continue;
}
//获取资源的名称
fileName = resource.getFilename();
try {
//添加附件
mimeMessageHelper.addAttachment(fileName, resource);
} catch (MessagingException e) {
e.printStackTrace();
log.error("邮件->{} 添加附件->{} 出现异常->{}", subject, attachmentFilePath, e.getMessage());
}
}
}
}
}
测试类控制层api
import com.xuan.common.mailer.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 测试发送邮件
* @author Xuan
* @date 2019/8/10 15:50
*/
@RestController
public class TestMailerSend {
@Autowired
private MailService mailService;
@RequestMapping(value = "/send")
public String send(){
mailService.sendSimpleTextMailActual("发送主题","发送内容",new String[]{"public_class_xuan@163.com"},null,null,null);
return "1";
}
}
调用控制层api地址 http://localhost:8080/send 查看效果
补充一些其他发送方式,注意要添加JavaMailSender注入
简单邮件
@Autowired
private JavaMailSender javaMailSender;
@Test
public void send() throws UnsupportedEncodingException {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
// simpleMailMessage .setFrom("1285906731@qq.com");
//设置目标发送人
simpleMailMessage .setTo("1661982372@qq.com");
simpleMailMessage.setSubject("主题");
simpleMailMessage.setText("内容");
//自定义发件人名称
String nick = "";
try {
nick = javax.mail.internet.MimeUtility.encodeText("张三");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 设置发件人
simpleMailMessage.setFrom(String.valueOf(new InternetAddress("1285906731@qq.com", nick)));
javaMailSender.send(simpleMailMessage);//发送
System.out.println("成功");
}
html格式邮件
@Test
public void sendHTMLMail() throws MessagingException {
MimeMessage mimeMailMessage = null;
mimeMailMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
mimeMessageHelper.setFrom("1285906731@qq.com");
mimeMessageHelper.setTo("1661982372@qq.com");
mimeMessageHelper.setSubject("主题");
mimeMessageHelper.setText("<h1>hello</h1>", true);
javaMailSender.send(mimeMailMessage);
}
带附件格式的邮件
@Test
public void sendAttachmentMail() throws MessagingException {
MimeMessage mimeMailMessage = null;
mimeMailMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
mimeMessageHelper.setFrom("1285906731@qq.com");
mimeMessageHelper.setTo("1661982372@qq.com");
mimeMessageHelper.setSubject("主题");
mimeMessageHelper.setText("发送内容");
//文件路径 spring的FileSystemResource,使用绝对路径访问文件资源
FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/image/mail.jpg"));
mimeMessageHelper.addAttachment("mail.png", file);
javaMailSender.send(mimeMailMessage);
}
发送带静态资源的邮件
@Test
public void sendInlineMail() throws MessagingException {
MimeMessage mimeMailMessage = null;
mimeMailMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
mimeMessageHelper.setFrom("1285906731@qq.com");
mimeMessageHelper.setTo("1661982372@qq.com");
mimeMessageHelper.setSubject("主题");
mimeMessageHelper.setText("<html><body>带静态资源的邮件内容,这个一张IDEA配置的照片:<img src='cid:picture' /></body></html>", true);
//文件路径
FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/image/mail.jpg"));
mimeMessageHelper.addInline("picture", file);
javaMailSender.send(mimeMailMessage);
}
基于Freemarker的模板邮件
动态添加邮箱配置信息
public void sendSimpleMail() throws Exception {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();//直接生产一个实例
String users[] = {"xxxxx@qq.com","xxxxx@126.com"};
mailSender.setHost("smtp.126.com");//动态添加配置
mailSender.setPassword("xxxxx");
mailSender.setPort(25);
mailSender.setProtocol("smtp");
mailSender.setUsername("xxxxx");
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("xxxxxxx");
message.setTo(users); // 使用数组的形式还可以群发
message.setSubject("羽毛球比赛");
message.setText("报名参加羽毛球赛");
mailSender.send(message);
}