前言
❤Java学习路线个人总结-博客
❤欢迎点赞👍收藏⭐留言 📝分享给需要的小伙伴
SpringBoot发送邮件
-
如有问题麻烦请指出,互相学习。谢谢!
-
此mail支持嵌入式图片,支持附件上传,和普通基本邮件服务。
-
之前嵌入图片采用这种流的方式,不知道为什么总是不成功。只好将返回的流又重新保存了临时文件,成功后在将临时文件删除,如果有大佬解决了此类问题,麻烦评论指出。
//嵌入资源,嵌入资源图片,将图片文件流嵌入到HTML当中
helper.addInline(imgPath,new ByteArrayResource(IOUtils.toByteArray(inputStream)), ContentTypes.getContentTypeFromFileExtension(imgPath));
yml
spring:
profiles:
active: dev
mail:
#邮箱服务器地址
host: smtp.qq.com
#用户名
username: xx@qq.com
#密码
password: xxx
#编码格式
default-encoding: utf-8
#邮件服务端口25为smtp
port: 25
#通信协议
protocol: smtp
POM
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
modal
/**
* 接收方
*/
@NotEmpty
@Transient
private String[] to;
/**
* 抄送
*/
@Transient
private String[] cc;
/**
* 密送
*/
@Transient
private String[] bcc;
/**
* 主题
*/
@NotNull //不能为NULL可以为""
@Transient
private String subject;
/**
* 内容
*/
@NotNull //不能为NULL可以为""
@Transient
private String text;
/**
* 昵称
*/
@Transient
@JsonProperty(value = "nike_name")
private String nickName;
/**
* 图片名称
*/
@Transient
@JsonProperty(value = "img_path")
private String[] imgPath;
/**
* 附件信息
* 附件信息,key为原始文件名,value为上传完成问文件名
*/
@Transient
private Map<String, Object> attachments;
controller
public Info sendEmail(@RequestBody @Valid Email email) {
Info info = new Info();;
if (email.getTo() == null || email.getTo().length == 0) {
info.setSuccess(false);
info.setDescription("请输入收件人邮箱!");
} else {
//复杂邮件
if (email.getAttachments() != null || email.getImgPath() != null) {
info = testService.sendComplexEmail(email,info);
} else {
//简单邮件
info = testService.sendSimpleEmail(email,info);
}
}
return info;
}
service
boolean sendComplexEmail(Email email,Info info);
boolean sendSimpleEmail(Email email,Info info);
impl
private final Logger logger = LoggerFactory.getLogger(TestServiceImpl.class);
@Autowired
private JavaMailSender mailSender;
@Autowired
private FileFeignClient fileFeignClient;
@Value("${spring.mail.username}")
private String from;
/**
* <p>发送复杂邮件</p>
* @param: email
*/
@Override
public Info sendComplexEmail(Email email, Info info) {
try {
//存放临时文件地址
List<String> imgPathList = new ArrayList<>();
//解决附件名称过长,出现错误附件名称。连接邮件服务器的参数配置附件名称过长乱码解决
System.getProperties().setProperty("mail.mime.splitlongparameters", "false");
//复杂邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
//如果想要带附件图片 必须指定multipart参数为true
MimeMessageHelper helper = null;
helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
//设置基本信息
buildBasicMessage(email, helper);
//如果邮件内容没有img标签,并且上传了图片,如果图片没有嵌入则会变为附件上传
buildImgs(email, imgPathList, helper);
//设置附件
buildAttachment(email, helper);
//发送复杂邮件
mailSender.send(mimeMessage);
//删除临时文件
if (imgPathList.size() > 0) {
for (String path : imgPathList) {
Filedelete(path);
}
}
info.setSuccess(true);
info.setDescription("邮件发送成功");
return info;
} catch (MessagingException | IOException e) {
logger.error("发送邮件失败", e);
info.setDescription("发送邮件失败");
info.setSuccess(false);
return info;
}
}
/**
* <p>发送普通附件</p>
* @param: email
*/
@Override
public Info sendSimpleEmail(Email email, Info info) {
try {
//普通邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
//设置邮件基本信息
buildBasicMessage(email, helper);
//发送简单邮件
mailSender.send(mimeMessage);
info.setSuccess(true);
info.setDescription("邮件发送成功");
return info;
} catch (MessagingException | UnsupportedEncodingException e) {
logger.error("发送邮件失败", e);
info.setDescription("发送邮件失败");
info.setSuccess(false);
return info;
}
}
/**
* <p>设置基本信息</p>
* @param: email 邮件对象
* @Param helper 组件
*/
public void buildBasicMessage(Email email, MimeMessageHelper helper) throws MessagingException, UnsupportedEncodingException {
//设置发送人,发送人昵称
helper.setFrom(from, email.getNickName());
//设置收件人
if (email.getTo() != null) {
helper.setTo(email.getTo());
}
//设置抄送人
if (email.getCc() != null) {
helper.setCc(email.getCc());
}
//设置密送人
if (email.getBcc() != null) {
helper.setBcc(email.getBcc());
}
//设置标题
helper.setSubject(email.getSubject());
//设置内容,HTML,文本
helper.setText(email.getText(), true);
}
/**
* <p>构建附件</p>
* @param: email 邮件消息对象
* @Param helper 组件
*/
public void buildAttachment(Email email, MimeMessageHelper helper) throws MessagingException, IOException {
if (email.getAttachments() != null && email.getAttachments().size() > 0) {
for (Map.Entry<String, Object> attachments : email.getAttachments().entrySet()) {
Response response = fileFeignClient.downFile((String) attachments.getValue());
//附件名称要采用原始名称,通过文件流方式上传附件
helper.addAttachment(attachments.getKey(), new ByteArrayResource(IOUtils.toByteArray(response.body().asInputStream())));
}
}
}
/**
* <p>构建嵌入图片</p>
* @param: email 邮件对象
* @Param imgPathList 临时路径集合
* @Param helper 组件
*/
public void buildImgs(Email email, List<String> imgPathList, MimeMessageHelper helper) throws MessagingException {
if (email.getImgPath() != null && email.getImgPath().length > 0) {
for (String imgPath : email.getImgPath()) {
//获得临时文件路径
String filePath = getFilePath(imgPath);
//获取文件
FileSystemResource file = new FileSystemResource(new File(filePath));
if (!file.exists()) {
throw new RestResouceNotFoundException("文件不存在!");
}
//嵌入资源,嵌入资源图片,将图片文件流嵌入到HTML当中
helper.addInline(imgPath, file);
//存放临时文件地址
imgPathList.add(filePath);
}
}
}
/**
* <p>保存图片到临时文件夹</p>
*
* @param: fileName 上传完成图片名称
* @return: java.lang.String
*/
public String getFilePath(String fileName) {
InputStream inputStream = null;
//获得文件流
Response response = fileFeignClient.downFile(fileName);
Response.Body body = response.body();
String filePath = "";
FileOutputStream fos = null;
try {
//获取response中的文件流
inputStream = body.asInputStream();
//临时目录
String folder = System.getProperty("java.io.tmpdir");
int random = (int) (1 + Math.random() * (10 - 1 + 1));
String sj = String.valueOf(DateUtil.getCurrentDate().getTime());
//临时路径+文件名称
filePath = folder + sj + random + fileName.substring(fileName.lastIndexOf("."));
//写入文件
fos = new FileOutputStream(filePath);
byte[] c = new byte[1024];
int length;
while ((length = inputStream.read(c)) > 0) {
fos.write(c, 0, length);
}
} catch (IOException e1) {
throw new Exception("上传临时文件错误,错误原因:" + e1);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
throw new Exception("流关闭异常,错误原因:" + e);
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
throw new Exception("流关闭异常,错误原因:" + e);
}
}
}
return filePath;
}
/**
* <p>删除临时文件</p>
* @param: fileName 文件地址
* @return: boolean
*/
public boolean Filedelete(String fileName) {
File file = new File(fileName);
if (!file.exists()) {
logger.error("删除文件失败:" + fileName + "不存在!");
return false;
} else {
// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
if (file.exists() && file.isFile()) {
if (file.delete()) {
logger.info("删除单个文件" + fileName + "成功!");
return true;
} else {
logger.error("删除单个文件" + fileName + "失败!");
return false;
}
} else {
logger.error("删除单个文件失败:" + fileName + "不存在!");
return false;
}
}
}
测试代码
package com.sbr;
import org.junit.Test;
import org.junit.runner.RunWith;
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.boot.test.context.SpringBootTest;
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.test.context.junit4.SpringRunner;
import javax.mail.Message;
import javax.mail.internet.MimeMessage;
import java.io.File;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
/**
* setText 指定邮件内容,如果设置Ture则支持Html内容,如果不设置默认按字符串处理
* MimeMessageHelper 邮件消息,如果不指定True则不支持,附件,图片等类型
* JavaMailSender 发送邮件对象
* SimpleMailMessage 普通邮件消息对象
* MimeMessageHelper 特殊邮件消息对象,需要对MimeMessage进行包装
* MimeMessage 属于是MIME类型的邮件消息,MIME 消息能包含文本、图像、音频、视频以及其他应用程序专用的数据。
* To Cc Bcc 发送,抄送,密送
* System.getProperties().setProperty("mail.mime.splitlongparameters", "false"); 解决附件名称过长,出现错误附件名称
*
*
*/
/**
* <p>普通文本邮件</p>
* @param:
* @return: void
*/
@Test
public void testMail(){
//普通文本类型邮件采用 SimpleMailMessage
SimpleMailMessage mimeMessage = new SimpleMailMessage();
mimeMessage.setFrom(from);//发送者
mimeMessage.setTo("xxx@163.com");//接收者
mimeMessage.setSubject("SpringBoot集成JavaMail实现邮件发送");//邮件主题
mimeMessage.setText("SpringBoot集成JavaMail实现邮件发送正文");//邮件内容
mailSender.send(mimeMessage);
System.out.println("发送成功");
}
/**
* 发送图片邮件
*
* @throws Exception
*/
@Test
public void sendImageMail(){
//MailMessasge 邮件消息包装,创建消息对象,特殊邮件采用方式
MimeMessage message = mailSender.createMimeMessage();
//邮件消息的helper MimeMessageHelper,使用helper来包装MimeMessage
MimeMessageHelper helper = null;
try{
helper = new MimeMessageHelper(message,true);//如果想要带附件图片 加上true
helper.setFrom(from);//发件人
message.addRecipients(Message.RecipientType.TO,"xxx@qq.com");//收件人
message.addRecipients(Message.RecipientType.CC, "xxx@163.com");//抄送
//message.addRecipients(Message.RecipientType.BCC, "xxx@163.com");//密送
//helper.setTo(to);//单独接收方
helper.setSubject("邮件主题");//邮件主题
String html = "<html><body><img src='cid:resource1234'></body></html>";
helper.setText(html,true);//邮件内容,如果不设置True全部按照字符串处理,如果设置True解析Html内容
FileSystemResource file = new FileSystemResource(new File("E:\\4cda0594-b50b-4cb3-93b3-d2db095e0a63.jpg"));
//
helper.addInline("resource1234",file);//嵌入资源,嵌入资源图片,将上传的图片嵌入到HTML当中
mailSender.send(message);
logger.info("发送静态图片邮件成功!");
}catch (Exception e){
logger.error("发送静态邮件失败!",e);
}
}
/**
* 发送带副本的邮件
*
*/
@Test
public void sendAttachmentMail() throws Exception {
//解决附件名称过长,出现错误附件名称。连接邮件服务器的参数配置附件名称过长乱码解决
System.getProperties().setProperty("mail.mime.splitlongparameters", "false");
//邮件消息
MimeMessage message = mailSender.createMimeMessage();
//邮件消息的helper MimeMessageHelper,使用helper来包装MimeMessage
MimeMessageHelper helper = new MimeMessageHelper(message,true);//如果想要带附件图片 加上true
helper.setFrom(from);//发送方
helper.setTo("xxx@163.com");//接收方
helper.setSubject("邮件主题");//邮件主题
helper.setText("邮件内容");//内容
FileSystemResource file = new FileSystemResource(new File("E:\\222222222222222222222222222222222222222222222222222222222222222222222222222.jpg"));
String filename = file.getFilename();
helper.addAttachment(filename,file);//附件
//进行发送
mailSender.send(message);
logger.info("副本邮件发送成功!");
}
/**
* 发送HTML邮件
*/
@Test
public void sendHtmlMail() throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
helper.setFrom(from);//发送方
helper.setTo("xxx@163.com");//接收方
helper.setSubject("邮件主题");//邮件主题
String html = "<html><body><h3>hello world!测试发送html格式邮件</h3></body></html>";
helper.setText(html,true);//内容
mailSender.send(mimeMessage);
logger.info("HTML邮件发送成功!");
}
@Test
public void sendImageMail1(){
//MailMessasge 邮件消息包装
MimeMessage message = mailSender.createMimeMessage();
//邮件消息的helper MimeMessageHelper,使用helper来包装MimeMessage
MimeMessageHelper helper = null;
try{
helper = new MimeMessageHelper(message, true);
helper.setFrom(from);//发件人
message.addRecipients(Message.RecipientType.TO,"xxx@qq.com");//收件人
message.addRecipients(Message.RecipientType.CC, "xxx@163.com");//抄送
//helper.setTo(to);//接收方
helper.setSubject("邮件主题");//邮件主题
String html = "<html><body><h3>hello world!测试发送html格式邮件</h3></body></html>";
helper.setText(html,false);//邮件内容,如果为false则不支持HTML格式的内容,按字符串处理,如果为true则按照html去进行解析
FileSystemResource file = new FileSystemResource(new File("E:\\4cda0594-b50b-4cb3-93b3-d2db095e0a63.jpg"));
helper.addInline("resource1234",file);//嵌入资源
mailSender.send(message);
logger.info("发送静态图片邮件成功!");
}catch (Exception e){
logger.error("发送静态邮件失败!",e);
}
}
}