直接引入整合后的官方依赖
一、Springboot整合mail
配置
org.springframework.boot
spring-boot-starter-mail
以QQ邮箱为例,开启授权码,粘贴到配置文件中的password项
application.yml配置
spring:
mail:
#smtp服务主机 qq邮箱则为smtp.qq.com、smtp.163.com
host: smtp.qq.com
#服务协议
protocol: smtp
# 编码集
default-encoding: UTF-8
#发送者邮件的账户
username: [email protected]
#发送者邮箱授权码
password: sadfasdggh
test-connection: true
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
controller
package priv.yuey.wheels.emailDemo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import priv.yuey.wheels.commonUtilsDemo.ResponseData;
import priv.yuey.wheels.emailDemo.SimpleEmailEntity;
import priv.yuey.wheels.emailDemo.service.EmailService;
/**
* @Author yue
* @Date 2022-01-02
* @Version V1.0.1
* @Description 邮箱服务接口
*/
@RestController
@RequestMapping("email")
public class EmailController {
@Autowired
private EmailService emailService;
/**
* 发送文本邮件
*/
@PostMapping("text")
public ResponseData sendTestEmail(@RequestBody SimpleEmailEntity simpleEmailEntity){
return emailService.sendTextMail(simpleEmailEntity);
}
/**
* 发送html邮件
*/
@PostMapping("html")
public ResponseData sendEmail(@RequestBody SimpleEmailEntity simpleEmailEntity){
return emailService.sendHtmlMail(simpleEmailEntity);
}
/**
* 发送附件邮件
*/
@PostMapping("attachments")
public ResponseData sendAttachmentsMail(@RequestBody SimpleEmailEntity simpleEmailEntity){
return emailService.sendAttachmentsMail(simpleEmailEntity);
}
}
=================================================================================== 参数类
=================================================================================== 参数类
=================================================================================== 参数类
package priv.yuey.wheels.emailDemo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Author yue
* @Date 2022-01-02
* @Version V1.0.1
* @Description
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SimpleEmailEntity {
/**
* 主题
*/
private String subject;
/**
* 主题内容
*/
private String text;
/**
* 接收人邮箱列表
*/
private String tos;
// private String[] tos;
/**
* 附件路径
*/
private String filePath;
}
Service
package priv.yuey.wheels.emailDemo.service;
import org.springframework.mail.SimpleMailMessage;
import priv.yuey.wheels.commonUtilsDemo.ResponseData;
import priv.yuey.wheels.emailDemo.SimpleEmailEntity;
/**
* @Author yue
* @Date 2022-01-02
* @Version V1.0.1
* @Description 邮箱服务
*/
public interface EmailService {
/**
* 发送文本邮件
* @param simpleEmailEntity 邮件信息
*/
ResponseData sendTextMail(SimpleEmailEntity simpleEmailEntity);
/**
* 发送HTML邮件
* @param simpleEmailEntity 邮件信息
*/
ResponseData sendHtmlMail(SimpleEmailEntity simpleEmailEntity);
/**
* 发送带附件的邮件
* @param simpleEmailEntity 邮件信息
* @param filePath 附件路径
*/
ResponseData sendAttachmentsMail(SimpleEmailEntity simpleEmailEntity);
}
=================================================================================== 实现类
=================================================================================== 实现类
=================================================================================== 实现类
package priv.yuey.wheels.emailDemo.service.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 priv.yuey.wheels.commonUtilsDemo.ResponseData;
import priv.yuey.wheels.emailDemo.SimpleEmailEntity;
import priv.yuey.wheels.emailDemo.service.EmailService;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
/**
* @Author yue
* @Date 2022-01-02
* @Version V1.0.1
* @Description 邮箱服务
*/
@Service
public class EmailServiceImpl implements EmailService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${spring.mail.username}")
private String from;
@Autowired
private JavaMailSender mailSender;
@Override
public ResponseData sendTextMail(SimpleEmailEntity simpleEmailEntity) {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
//发件人
simpleMailMessage.setFrom(from);
//收件人
simpleMailMessage.setTo(simpleEmailEntity.getTos());
//邮件主题
simpleMailMessage.setSubject(simpleEmailEntity.getSubject());
//邮件内容
simpleMailMessage.setText(simpleEmailEntity.getText());
//发送邮件
mailSender.send(simpleMailMessage);
return ResponseData.ok("邮件发送成功");
}
@Override
public ResponseData sendHtmlMail(SimpleEmailEntity simpleEmailEntity) {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper messageHelper;
try {
messageHelper = new MimeMessageHelper(message,true);
messageHelper.setFrom(from);
messageHelper.setTo(simpleEmailEntity.getTos());
message.setSubject(simpleEmailEntity.getSubject());
messageHelper.setText(simpleEmailEntity.getText(),true);
mailSender.send(message);
logger.info("邮件已经发送!");
} catch (MessagingException e) {
logger.error("发送邮件时发生异常:"+e);
return ResponseData.ok("邮件发送失败");
}
return ResponseData.ok("邮件发送成功");
}
@Override
public ResponseData sendAttachmentsMail(SimpleEmailEntity simpleEmailEntity) {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper messageHelper;
String filePath = simpleEmailEntity.getFilePath();
try {
messageHelper = new MimeMessageHelper(message,true);
messageHelper.setFrom(from);
messageHelper.setTo(simpleEmailEntity.getTos());
messageHelper.setSubject(simpleEmailEntity.getSubject());
messageHelper.setText(simpleEmailEntity.getText(),true);
//携带附件
File file = new File(filePath);
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
messageHelper.addAttachment(fileName,file);
mailSender.send(message);
logger.info("邮件加附件发送成功!");
} catch (MessagingException e) {
logger.error("发送失败:"+e);
return ResponseData.ok("邮件发送失败");
}
return ResponseData.ok("邮件发送成功");
}
}
后续逻辑根据自己业务来
例如:邮箱校验用户(类似于手机号校验)、定时任务邮箱推送xx信息
pom.xml引入maven依赖
javax.mail
mail
1.4.7
具体实现
调用过程就不放了,比较简单
请求数据参考:
url:http://localhost:8080/email/sendMixedMail
{
"subject": "测试主题",
"content": "测试正文内容safds63369",
"tos": "接受邮件的邮箱地址",
"cc": "抄送人,下面代码暂时没添加抄送人,所以这个值无所谓",
"attachmentsPath": "附件地址,需要就添加,不需要无所谓。例如:D:\em\企业微信截图.png"
}
package priv.yuey.wheels.emailDemo.service.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import priv.yuey.wheels.commonUtilsDemo.ResponseData;
import priv.yuey.wheels.emailDemo.SimpleEmailEntity;
import priv.yuey.wheels.emailDemo.service.EmailService;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
/**
* @Author yue
* @Date 2022-01-02
* @Version V1.0.1
* @Description 邮箱服务
*/
@Service
public class EmailServiceImpl implements EmailService {
private final Logger logger = LoggerFactory.getLogger(EmailService.class);
// @Value("${spring.mail.username}")
private static final String from = "发送人邮箱@qq.com";
private static final String mailHost = "smtp.qq.com";// 具体邮箱服务类型来写,这是qq邮箱的
private static final String mailPassword = "fdsgfdsggf";// 邮箱密码,参考文章顶部图片
private static final String mailTransportProtocol = "smtp";
private static final String mailSmtpAuth = "true";// 开启密码校验,默认关闭的。
@Override
public ResponseData sendTextMail(SimpleEmailEntity simpleEmailEntity) {
try {
Properties properties = emailConfig();
Session session = Session.getInstance(properties);
//2、通过session得到transport对象
Transport transport = session.getTransport();
//3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。
transport.connect(mailHost, from, mailPassword);
// 4、创建消息
MimeMessage message = new MimeMessage(session);
//指明邮件的发件人
message.setFrom(new InternetAddress(from));
//指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
message.setRecipient(Message.RecipientType.TO, new InternetAddress(simpleEmailEntity.getTos()));
//邮件的标题
message.setSubject(simpleEmailEntity.getSubject(),"UTF-8");
//邮件的文本内容
message.setContent(simpleEmailEntity.getContent(), "text/html;charset=UTF-8");
//返回创建好的邮件对象
//5、发送邮件
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (Exception e) {
logger.error("发送失败", e);
}
return ResponseData.ok("邮件发送成功");
}
@Override
public ResponseData sendAttachmentsMail(SimpleEmailEntity simpleEmailEntity) {
try {
Properties properties = emailConfig();
Session session = Session.getInstance(properties);
//2、通过session得到transport对象
Transport transport = session.getTransport();
//3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。
transport.connect(mailHost, from, mailPassword);
// 4、创建消息
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(simpleEmailEntity.getTos()));
message.setSubject(simpleEmailEntity.getSubject(),"UTF-8");
//创建邮件正文,为了避免邮件正文中文乱码问题,需要使用charset=UTF-8指明字符编码
MimeBodyPart text = new MimeBodyPart();
text.setContent(simpleEmailEntity.getContent(), "text/html;charset=UTF-8");
//创建邮件附件
MimeBodyPart attach = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource(simpleEmailEntity.getAttachmentsPath()));
attach.setDataHandler(dh);
attach.setFileName(MimeUtility.encodeText(dh.getName()));
//创建容器描述数据关系
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(text);
mp.addBodyPart(attach);
mp.setSubType("mixed");
message.setContent(mp);
message.saveChanges();
//5、发送邮件
transport.sendMessage(message, message.getAllRecipients());
transport.close();
logger.info("邮件发送成功,收件人:{}", simpleEmailEntity.getTos());
} catch (Exception e) {
logger.error("发送附件邮件错误!", e);
}
return ResponseData.ok("邮件发送成功");
}
/**
* 生成一封邮件正文带图片的邮件
*/
@Override
public ResponseData sendImageMail(SimpleEmailEntity simpleEmailEntity) {
try {
Properties properties = emailConfig();
Session session = Session.getInstance(properties);
Transport transport = session.getTransport();
transport.connect(mailHost, from, mailPassword);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(simpleEmailEntity.getTos()));
message.setSubject("带图片的邮件","UTF-8");
// 准备邮件数据
// 1、准备图片数据
MimeBodyPart image = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource("D:\\em\\企业微信截图.png"));
image.setDataHandler(dh);// 将图片数据添加到"节点"
image.setContentID("cstp");// 这个编号可在文本中引用
// 2、准备邮件正文数据
MimeBodyPart text = new MimeBodyPart();
text.setContent("这是一封邮件正文带图片的邮件", "text/html;charset=UTF-8");
// 3、描述数据关系
MimeMultipart mm = new MimeMultipart();
mm.addBodyPart(text);
mm.addBodyPart(image);
mm.setSubType("related");// 关联关系
message.setContent(mm);
//设置邮件的发送时间,默认立即发送
message.setSentDate(new Date());
message.saveChanges();
//发送邮件
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (Exception e) {
logger.error("发送邮件失败", e);
}
return ResponseData.ok("邮件发送成功");
}
/**
* 生成一封带附件和带图片的邮件
*/
@Override
public ResponseData sendMixedMail(SimpleEmailEntity simpleEmailEntity) {
try {
Properties properties = emailConfig();
Session session = Session.getInstance(properties);
//2、通过session得到transport对象
Transport transport = session.getTransport();
//3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。
transport.connect(mailHost, from, mailPassword);
// 4、创建消息
MimeMessage message = new MimeMessage(session);
//设置邮件的基本信息
message.setFrom(new InternetAddress(from));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(simpleEmailEntity.getTos()));
message.setSubject("带附件和带图片的的邮件");
// 准备邮件数据
// 1、准备图片数据
MimeBodyPart image = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource("D:\\em\\企业微信截图.png"));
image.setDataHandler(dh);// 将图片数据添加到"节点"
image.setContentID("cstp");// 这个编号可在文本中引用
// 2、准备邮件正文数据
MimeBodyPart text = new MimeBodyPart();
text.setContent("这是一封邮件正文带图片的邮件", "text/html;charset=UTF-8");
//描述关系:正文和图片
MimeMultipart mm_text_image = new MimeMultipart();
mm_text_image.addBodyPart(text);
mm_text_image.addBodyPart(image);
mm_text_image.setSubType("related");// 关联关系
// 讲图片、文本转成普通节点
MimeBodyPart text_image = new MimeBodyPart();
text_image.setContent(mm_text_image);
//附件1
MimeBodyPart attach1 = new MimeBodyPart();
DataHandler dh2 = new DataHandler(new FileDataSource("D:\\em\\滴滴出行电子发票及行程报销单.zip"));
attach1.setDataHandler(dh2);
attach1.setFileName(MimeUtility.encodeText(dh2.getName()));
//附件2
MimeBodyPart attach2 = new MimeBodyPart();
DataHandler dh3 = new DataHandler(new FileDataSource("D:\\em\\滴滴出行行程报销单.pdf"));
attach2.setDataHandler(dh3);
attach2.setFileName(MimeUtility.encodeText(dh3.getName()));
// 10. 大汇总:设置(文本+图片)的节点 和 附件 节点 的关系(合成一个大的混合"节点" / Multipart )
MimeMultipart mm = new MimeMultipart();
mm.addBodyPart(text_image);
mm.addBodyPart(attach1); // 如果有多个附件,可以创建多个多次添加
mm.addBodyPart(attach2); // 如果有多个附件,可以创建多个多次添加
mm.setSubType("mixed"); // 混合关系
message.setContent(mm);
message.saveChanges();
//5、发送邮件
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (Exception e) {
logger.error("发送邮件失败", e);
}
return ResponseData.ok("发送成功");
}
/**
* 邮箱基础配置
*/
public Properties emailConfig() {
Properties prop = new Properties();
prop.setProperty("mail.host", mailHost);
prop.setProperty("mail.transport.protocol", mailTransportProtocol);
prop.setProperty("mail.smtp.auth", mailSmtpAuth);
return prop;
}
}