package com.thk.utils;
import com.thk.domain.MailAccounts;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.Date;
import java.util.Properties;
public class MailSendUtils {
public void send(MailAccounts mailAccounts) throws Exception {
Message message = getMessage(mailAccounts);
// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart multipart = new MimeMultipart();
// 创建一个包含HTML内容的MimeBodyPart
BodyPart htmlOrTest = new MimeBodyPart();
if (mailAccounts.getIsHtml()) {
// 设置HTML内容
htmlOrTest.setContent(mailAccounts.getContent(), "text/html; charset=utf-8");
} else {
htmlOrTest.setText(mailAccounts.getContent());
}
// 添加发送内容
multipart.addBodyPart(htmlOrTest);
if (mailAccounts.getFileUploadNames() != null) {
// 添加附件
for (String fileName : mailAccounts.getFileUploadNames()) {
addEnclosure(multipart, fileName);
}
}
// 将MiniMultipart对象设置为邮件内容
message.setContent(multipart);
Transport.send(message);
}
private static void addEnclosure(Multipart multipart, String fileName) throws Exception {
BodyPart adjunct = new MimeBodyPart();
FileDataSource fileDataSource = new FileDataSource(fileName);
adjunct.setDataHandler(new DataHandler(new URL(fileName)));
adjunct.setFileName(changeEncode(fileDataSource.getName()));
multipart.addBodyPart(adjunct);
}
public static String changeEncode(String str) {
try {
str = MimeUtility.encodeText(new String(str.getBytes(), "UTF-8"),
"UTF-8", "B"); // "B"代表Base64
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return str;
}
private static Message getMessage(MailAccounts mailAccounts) throws Exception {
final Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", mailAccounts.getHost());
properties.setProperty("mail.smtp.auth", mailAccounts.getAuth().toString());
properties.setProperty("mail.smtp.user", mailAccounts.getFrom());
properties.setProperty("mail.smtp.pass", mailAccounts.getPass());
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); //使用JSSE的SSL socketfactory来取代默认的socketfactory
properties.put("mail.smtp.socketFactory.fallback", "false"); // 只处理SSL的连接,对于非SSL的连接不做处理
properties.put("mail.smtp.port", mailAccounts.getPort());
properties.put("mail.smtp.socketFactory.port", mailAccounts.getPort());
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session session = Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(properties.getProperty("mail.smtp.user"), properties.getProperty("mail.smtp.pass"));
}
});
session.setDebug(true);
Message message = new MimeMessage(session);
//消息发送的主题
message.setSubject(mailAccounts.getSubject());
//消息的发送者
message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.user"), mailAccounts.getPersonal()));
if (mailAccounts.getTo().length <= 0) {
throw new Exception("收件人不能为空!!");
}
for (String strAdd : mailAccounts.getTo()) {
// 创建邮件的接收者地址,并设置到邮件消息中
message.setRecipient(Message.RecipientType.TO, new InternetAddress(strAdd));
}
// 消息发送的时间
message.setSentDate(new Date());
return message;
}
}
二、实体类
package com.thk.domain;
import lombok.*;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MailAccounts {
private String host;
private Integer port;
private Boolean auth = true;
private String from;
private String user;
private String pass = "授权码" ;
private String toAddress;
private String subject;
private String content;
private Boolean isHtml = false;
private String personal;
private String[] to;
private String[] fileUploadNames = null;
public void setTo(String... to) {
this.to = to;
}
public void setFileUploadNames(String... fileUploadNames) {
this.fileUploadNames = fileUploadNames;
}
}
说明:实体类中的授权码需要到QQ邮箱当中获取
详见:https://jingyan.baidu.com/article/456c463b42f55e4b59314468.html
三、测试代码:
public static void main(String[] args) {
MailSendUtils mailSendUtils = new MailSendUtils();
MailAccounts mailAccounts = new MailAccounts();
mailAccounts.setHost("smtp.qq.com");//邮件地址
mailAccounts.setPort(465);//端口号
mailAccounts.setFrom("");//发送方地址
mailAccounts.setSubject("测试发送邮件");//发送主题
mailAccounts.setContent("测试发送邮件");//发送内容
mailAccounts.setPersonal("测试发送邮件");//发送者名称
mailAccounts.setTo("");//对象邮箱
mailAccounts.setIsHtml(true);
try {
mailSendUtils.send(mailAccounts);
System.out.println("发送成功!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("发送失败!"+e.getMessage());
}
}
运行结果:



