业务:
服务器与邮件服务器网络不互通,既应用服务器不能访问邮箱服务器网络,无法直接发送邮件
添加中间键进行邮件转发
应用服务器→中间键→邮件服务器
附件接口与邮件接口分开,方便发送有附件和无附件两种情况邮件
这里由于没用redis临时将附件id存入静态变量
附件改为多附件 ( 2020-12-18
@PostMapping(value="sendMail",consumes = {MediaType.MULTIPART_FORM_DATA_VALUE},produces = {MediaType.APPLICATION_JSON_VALUE})
public void sendMail(String mail,String title,String content,@RequestPart("files") List<MultipartFile> MultipartFiles){
try {
Properties prop = new Properties();
prop.setProperty("mail.host", "smtp.qq.com");// 设置邮件服务器主机名
prop.setProperty("mail.transport.protocol", "smtp");// 发送邮件协议名称
prop.setProperty("mail.smtp.auth", "true");// 发送服务器需要身份验证
//使用JavaMail发送邮件的5个步骤
//1、创建session
Session session = Session.getInstance(prop);
//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
session.setDebug(false);
//2、通过session得到transport对象
Transport ts = session.getTransport();
ts.connect("smtp.qq.com", "这是邮箱账号(无@qq.com)", "这是密码");//使用邮箱的用户名和密码连上邮件服务器(用户名只需写@前面的即可)
List<File> files = MultipartFileToFile(MultipartFiles); //MultipartFile 转 File
//4、创建邮件
Message message = createSimpleMail(session,mail,title,content,files);
//5、发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
delteTempFile(toFile);
} catch (Exception e) {
e.printStackTrace();
}
}
public static MimeMessage createSimpleMail(Session session,String mail,String title,String content,List<File> Files) throws Exception {
//创建邮件对象
MimeMessage message = new MimeMessage(session);
//指明邮件的发件人
message.setFrom(new InternetAddress("邮箱账号@qq.com"));
//指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
message.setRecipient(Message.RecipientType.TO, new InternetAddress("账号@qq.com"));
// // 发送给多个收件人
// message.setRecipients(Message.RecipientType.TO, new InternetAddress[] {});
// // Cc: 抄送(可选)
// message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress(""));
// // Bcc: 密送(可选)
// message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress(""));
//邮件的标题
message.setSubject(title);
// 创建容器描述数据关系
MimeMultipart mp = new MimeMultipart();
// 创建邮件正文
MimeBodyPart text = new MimeBodyPart();
text.setContent(content, "text/html;charset=UTF-8");
mp.addBodyPart(text);// 添加正文
// 创建附件
MimeBodyPart attach = null;
if(Files != null && Files.size() > 0) {
for (File file : Files) {
if(file != null) {
attach = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource(file));// 本地文件
attach.setDataHandler(dh);
attach.setFileName(dh.getName()); // 附件名
mp.addBodyPart(attach);// 添加附件
}
}
}
// 准备图片数据
// MimeBodyPart image = new MimeBodyPart();
// DataHandler dh1 = new DataHandler(new FileDataSource("src\\1.jpg"));
// image.setDataHandler(dh);
// image.setContentID("xxx.jpg");
mp.setSubType("mixed");
message.setContent(mp);
message.saveChanges();
//返回创建好的邮件对象
return message;
}
//MultipartFile 转 File
private static File MultipartFileToFile(List<MultipartFile> multipartFiles) throws Exception{
List<File> files = new ArrayList<File>();
File toFile = null;
if(multipartFiles != null && multipartFiles.size() > 0) {
InputStream ins = null;
for (MultipartFile multipartFile : multipartFiles) {
if(multipartFile != null && multipartFile.getSize() > 0) {
ins = multipartFile.getInputStream();
toFile = new File(multipartFile.getOriginalFilename());
inputStreamToFile(ins, toFile);
files.add(toFile);
}
}
ins.close();
}
return files;
}
//获取流文件
private static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除本地临时文件
* @param file
*/
public static void delteTempFile(List<File> files) {
if(files != null && files.size() > 0) {
for (File file : files) {
if (file != null) {
File del = new File(file.toURI());
del.delete();
}
}
}
}
MultipartFile 转 file:
private static List<File> MultipartFileToFile(List<MultipartFile> multipartFiles) throws Exception{
List<File> files = new ArrayList<File>();
File toFile = null;
if(multipartFiles != null && multipartFiles.size() > 0) {
InputStream ins = null;
for (MultipartFile multipartFile : multipartFiles) {
if(multipartFile != null && multipartFile.getSize() > 0) {
ins = multipartFile.getInputStream();
toFile = new File(multipartFile.getOriginalFilename());
inputStreamToFile(ins, toFile);
files.add(toFile);
}
}
ins.close();
}
return files;
}
//获取流文件
private static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除本地临时文件
* @param file
*/
public static void delteTempFile(List<File> files) {
if(files != null && files.size() > 0) {
for (File file : files) {
if (file != null) {
File del = new File(file.toURI());
del.delete();
}
}
}
}
//20201223更
将附件与发送分开,
因为只是临时转发,数据不需要持久化,所以建立静态变量 fileMap 来临时存放附件信息。
上传附件,保存附件名字、路径 存储到list集合(名字用于发送时声明文件名,文件上传后需生成非中文路径,避免linux 中文乱码)
post请求: https://mp.csdn.net/editor/html/111592028
package com.example.demo.mail.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
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.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.example.demo.mail.model.Attachment;
import com.example.demo.mail.model.MailData;
import com.example.demo.mail.model.ResponseData;
@RestController
@RequestMapping("/mail")
@SuppressWarnings("all")
public class SendMail {
//未使用redis 存储邮件键值
private static HashMap<String, List<Attachment>> fileMap = new HashMap<>();
//此为中间键,先接受服务器发过来的附件,再和内容一起发送到邮件服务器,分开为方便发送不需要附件的邮件
@PostMapping(value="file",consumes = {MediaType.MULTIPART_FORM_DATA_VALUE},produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseData<String> file(@RequestPart("files") List<MultipartFile> MultipartFiles){
try {
//MultipartFile 转 File
List<Attachment> attachments = MultipartFileToFile(MultipartFiles);
String key = UUID.randomUUID().toString().replaceAll("-", "");
fileMap.put(key, attachments);
return ResponseData.success("邮件发送成功", key);
} catch (Exception e) {
e.printStackTrace();
}
return ResponseData.fail("邮件发送失败", "");
}
//http://localhost:8081/gxMail/mail/sendMail
@PostMapping(value="sendMail")
public ResponseData<String> sendMail(@RequestBody MailData mailData){
String smtpHost = "smtp.xxx.xxx.cn";
String smtpUser = "xxx@xxx.xxx.cn";
String smtpPwd = "xxxxx//";
String title = mailData.getTitle();
String content = mailData.getContent();
String sendFor = "xxx@xxx.xxx.cn";
String sendTo = mailData.getSendTo();
String key = mailData.getFileKey();
List<Attachment> attachments = null;
if(StringUtils.isNotBlank(key)) {
attachments = fileMap.get(key);
fileMap.remove(key);
}
if(StringUtils.isNotBlank(mailData.getSmtpHost())) {
smtpHost = mailData.getSmtpHost();
}
if(StringUtils.isNotBlank(mailData.getSmtpUser())) {
smtpUser = mailData.getSmtpUser();
}
if(StringUtils.isNotBlank(mailData.getSmtpPwd())) {
smtpPwd = mailData.getSmtpPwd();
}
if(StringUtils.isNotBlank(mailData.getSendFor())) {
sendFor = mailData.getSendFor();
}
if(StringUtils.isNotBlank(sendTo)) {
try {
Properties prop = new Properties();
prop.setProperty("mail.host", smtpHost);// 设置邮件服务器主机名 smtp.qq.com
prop.setProperty("mail.transport.protocol", "smtp");// 发送邮件协议名称 smtp
prop.setProperty("mail.smtp.auth", "true");// 发送服务器需要身份验证 true
//使用JavaMail发送邮件的5个步骤
//1、创建session
Session session = Session.getInstance(prop);
//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
session.setDebug(false);
//2、通过session得到transport对象
Transport ts = session.getTransport();
ts.connect(smtpHost, smtpUser, smtpPwd);//使用邮箱的用户名和密码连上邮件服务器(用户名只需写@前面的即可)
//4、创建邮件
Message message = createSimpleMail(session,sendFor,sendTo,title,content,attachments);
//5、发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
delteTempFile(attachments);
return ResponseData.success("邮件发送成功", sendTo);
} catch (Exception e) {
e.printStackTrace();
}
}
return ResponseData.fail("邮件发送失败", null);
}
/*
* mail 收件人邮箱
*
* **/
public static MimeMessage createSimpleMail(Session session,String sendFor,String sendTo,String title,String content,List<Attachment> attachments) throws Exception {
//创建邮件对象
MimeMessage message = new MimeMessage(session);
//指明邮件的发件人
message.setFrom(new InternetAddress(sendFor));
//指明邮件的收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(sendTo));
// // 发送给多个收件人
// message.setRecipients(Message.RecipientType.TO, new InternetAddress[] {});
// // Cc: 抄送(可选)
// message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress(""));
// // Bcc: 密送(可选)
// message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress(""));
//邮件的标题
message.setSubject(title);
// 创建容器描述数据关系
MimeMultipart mp = new MimeMultipart();
// 创建邮件正文
MimeBodyPart text = new MimeBodyPart();
text.setContent(content, "text/html;charset=UTF-8");
mp.addBodyPart(text);// 添加正文
// 创建附件
MimeBodyPart attach = null;
if(attachments != null && attachments.size() > 0) {
for (Attachment attachment : attachments) {
if(attachment != null) {
attach = new MimeBodyPart();
File file = new File(attachment.getAttPath());
DataHandler dh = new DataHandler(new FileDataSource(file));// 本地文件
attach.setDataHandler(dh);
attach.setFileName(attachment.getAttName()); // 附件名
mp.addBodyPart(attach);// 添加附件
}
}
}
// 准备图片数据
// MimeBodyPart image = new MimeBodyPart();
// DataHandler dh1 = new DataHandler(new FileDataSource("src\\1.jpg"));
// image.setDataHandler(dh);
// image.setContentID("xxx.jpg");
mp.setSubType("mixed");
message.setContent(mp);
message.saveChanges();
//返回创建好的邮件对象
return message;
}
private static List<Attachment> MultipartFileToFile(List<MultipartFile> multipartFiles) throws Exception{
List<Attachment> attachments = new ArrayList<Attachment>();
// List<File> files = new ArrayList<File>();
File toFile = null;
if(multipartFiles != null && multipartFiles.size() > 0) {
InputStream ins = null;
for (MultipartFile multipartFile : multipartFiles) {
if(multipartFile != null && multipartFile.getSize() > 0) {
ins = multipartFile.getInputStream();
String fileName = multipartFile.getOriginalFilename();
String newFileName = UUID.randomUUID().toString()+"."+fileName.substring(fileName.lastIndexOf(".") + 1);
String newFilePath = newFileName;
toFile = new File(newFilePath);
inputStreamToFile(ins, toFile);
// files.add(toFile);
attachments.add(new Attachment(multipartFile.getOriginalFilename(), toFile.getCanonicalPath()));
}
}
ins.close();
}
return attachments;
}
//获取流文件
private static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除本地临时文件
* @param file
*/
public static void delteTempFile(List<Attachment> attachments) {
if(attachments != null && attachments.size() > 0) {
for (Attachment attachment : attachments) {
if (attachment != null) {
File del = new File(attachment.getAttPath());
del.delete();
}
}
}
}
}
实体:Attachment
/**
*
*/
package com.example.demo.mail.model;
import java.io.Serializable;
/**
* @author
*
*/
public class Attachment implements Serializable {
private static final long serialVersionUID = 1L;
private String attName;
private String attPath;
public Attachment() {
// TODO Auto-generated constructor stub
}
public Attachment(String attName, String attPath) {
super();
this.attName = attName;
this.attPath = attPath;
}
public String getAttName() {
return attName;
}
public void setAttName(String attName) {
this.attName = attName;
}
public String getAttPath() {
return attPath;
}
public void setAttPath(String attPath) {
this.attPath = attPath;
}
}
package com.example.demo.mail.model;
import java.io.Serializable;
import org.springframework.http.HttpStatus;
/**
* 服务端响应数据
*/
public class ResponseData<T> implements Serializable {
private static final long serialVersionUID = 1L;
/**操作是否成功*/
private boolean success = false;
/**返回代码*/
private int code;
/**操作消息*/
private String msg = "";
/**数据对象*/
private T data = null;
public ResponseData() {
super();
}
public ResponseData(boolean success, int code, String msg, T data) {
super();
this.success = success;
this.code = code;
this.msg = msg;
this.data = data;
}
/**
*
* @title Json
* @Description Json
* @param msg
*/
public ResponseData(String msg) {
this.success = false;
this.code = HttpStatus.INTERNAL_SERVER_ERROR.value();
this.msg = msg;
}
public ResponseData(int code,String msg,T data) {
this.code = code;
this.success=HttpStatus.OK.value()==code?true:false;
this.msg = msg;
this.data = data;
}
public ResponseData(boolean success,String msg,T data) {
this.code = success?HttpStatus.OK.value():HttpStatus.INTERNAL_SERVER_ERROR.value();
this.success=success;
this.msg = msg;
this.data = data;
}
/**
* 失败静态方法
* @param msg
* @return
*/
public static <T> ResponseData<T> fail(String msg,T data){
return new ResponseData<T>(false,msg,data);
}
/**
* 成功的静态方法
* @param <T>
* @param msg
* @param data
* @return
*/
public static <T> ResponseData<T> success(String msg,T data){
return new ResponseData<T>(true, msg, data);
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
package com.example.demo.mail.model;
import java.io.Serializable;
public class MailData implements Serializable{
private static final long serialVersionUID = 1L;
private String smtpHost;
private String smtpUser;
private String smtpPwd;
private String title;
private String content;
private String sendFor;
private String sendTo;
private String fileKey;
public String getSmtpHost() {
return smtpHost;
}
public void setSmtpHost(String smtpHost) {
this.smtpHost = smtpHost;
}
public String getSmtpUser() {
return smtpUser;
}
public void setSmtpUser(String smtpUser) {
this.smtpUser = smtpUser;
}
public String getSmtpPwd() {
return smtpPwd;
}
public void setSmtpPwd(String smtpPwd) {
this.smtpPwd = smtpPwd;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getSendFor() {
return sendFor;
}
public void setSendFor(String sendFor) {
this.sendFor = sendFor;
}
public String getSendTo() {
return sendTo;
}
public void setSendTo(String sendTo) {
this.sendTo = sendTo;
}
public String getFileKey() {
return fileKey;
}
public void setFileKey(String fileKey) {
this.fileKey = fileKey;
}
}