需要实现邮件发送的功能,对过程进行一下记录。
① 首先需要开启邮箱的smtp服务,现在很多邮箱默认关闭smtp,pop3,imap服务,需要登录邮箱后在设置中手动开启。
② 引入Jakarta Mail依赖包
org.springframework.boot
spring-boot-starter-mail
③ 邮件信息对象
package com.changkong.util.email;
import com.sun.mail.util.MailSSLSocketFactory;
import java.security.GeneralSecurityException;
import java.util.List;
import java.util.Properties;
import lombok.Data;
@Data
public class MailSenderInfo {
// 发送邮件的服务器的IP和端口
private String mailServerHost;
private String mailServerPort = "465";
private boolean enableSSL;
private boolean enableTLS;
// 邮件发送者的地址
private String fromAddress;
// 邮件接收者的地址
private List toAddressList;
// 登陆邮件发送服务器的用户名和密码
private String userName;
private String password;
// 是否需要身份验证
private boolean validate = false;
// 邮件主题
private String subject;
// 邮件的文本内容
private String content;
// 邮件附件的文件名
private List attachFileNames;
/**
* 获得邮件会话属性
*/
public Properties getProperties() throws GeneralSecurityException {
Properties p = new Properties();
p.put("mail.smtp.host", this.mailServerHost);
p.put("mail.smtp.port", this.mailServerPort);
if (this.enableSSL) {
MailSSLSocketFactory sf = null;
sf = new MailSSLSocketFactory();
// 设置信任所有的主机
sf.setTrustAllHosts(true);
p.put("mail.smtp.ssl.enable", "true");
p.put("mail.smtp.ssl.socketFactory", sf);
}
p.put("mail.smtp.starttls.enable", enableTLS ? "true" : false);
p.put("mail.smtp.auth", validate ? "true" : "false");
return p;
}
}
④ 认证对象
package com.changkong.util.email;
import jakarta.mail.Authenticator;
import jakarta.mail.PasswordAuthentication;
public class MyAuthenticator extends Authenticator {
private String userName;
private String password;
public MyAuthenticator() {
}
public MyAuthenticator(String userName, String password) {
this.userName = userName;
this.password = password;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
}
⑤ 邮件发送工具类
package com.changkong.util.email;
import jakarta.activation.DataHandler;
import jakarta.activation.FileDataSource;
import jakarta.mail.*;
import jakarta.mail.internet.*;
import java.util.Date;
import java.util.Properties;
public class Email {
/**
* 以文本格式发送邮件
*
* @param mailInfo 待发送邮件信息
* @throws Exception
*/
public static void sendTextMail(MailSenderInfo mailInfo) throws Exception {
mailInfo.setSubject("测试邮件");
MimeMessage mailMessage = initMimeMessage(mailInfo);
// 设置邮件消息的主要内容
String mailContent = mailInfo.getContent();
mailMessage.setText(mailContent);
if (mailInfo.getAttachFileNames() != null) {
MimeMultipart multipart = new MimeMultipart();
for (String fileName : mailInfo.getAttachFileNames()) {
MimeBodyPart attachment = new MimeBodyPart();
// 读取本地文件
DataHandler dh2 = new DataHandler(new FileDataSource(fileName));
// 将附件数据添加到"节点"
attachment.setDataHandler(dh2);
// 设置附件的文件名(需要编码)
attachment.setFileName(MimeUtility.encodeText(dh2.getName()));
// 10. 设置(文本+图片)和 附件 的关系(合成一个大的混合"节点" / Multipart )
MimeMultipart mm = new MimeMultipart();
mm.addBodyPart(attachment); // 如果有多个附件,可以创建多个多次添加
mm.setSubType("mixed"); // 混合关系
multipart.addBodyPart(attachment);
}
mailMessage.setContent(multipart);
}
// 发送邮件
Transport.send(mailMessage);
}
/**
* 以HTML格式发送邮件
*
* @param mailInfo 待发送邮件信息
* @throws Exception
*/
public static void sendHtmlMail(MailSenderInfo mailInfo) throws Exception {
MimeMessage mailMessage = initMimeMessage(mailInfo);
Multipart multipart = new MimeMultipart();
if (mailInfo.getAttachFileNames() != null) {
for (String fileName : mailInfo.getAttachFileNames()) {
MimeBodyPart attachment = new MimeBodyPart();
// 读取本地文件
DataHandler dh2 = new DataHandler(new FileDataSource(fileName));
// 将附件数据添加到"节点"
attachment.setDataHandler(dh2);
// 设置附件的文件名(需要编码)
attachment.setFileName(MimeUtility.encodeText(dh2.getName()));
// 10. 设置(文本+图片)和 附件 的关系(合成一个大的混合"节点" / Multipart )
MimeMultipart mm = new MimeMultipart();
mm.addBodyPart(attachment); // 如果有多个附件,可以创建多个多次添加
mm.setSubType("mixed"); // 混合关系
multipart.addBodyPart(attachment);
}
mailMessage.setContent(multipart);
}
// 创建一个包含HTML内容的MimeBodyPart
BodyPart html = new MimeBodyPart();
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
multipart.addBodyPart(html);
// 将MiniMultipart对象设置为邮件内容
mailMessage.setContent(multipart);
// 发送邮件
Transport.send(mailMessage);
}
private static MimeMessage initMimeMessage(MailSenderInfo mailInfo) throws Exception {
// 判断是否需要身份认证
MyAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
if (mailInfo.isValidate()) {
// 如果需要身份认证,则创建一个密码验证器
authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
// 根据session创建一个邮件消息
MimeMessage mailMessage = new MimeMessage(sendMailSession);
// 创建邮件发送者地址
Address from = new InternetAddress(mailInfo.getFromAddress());
// 设置邮件消息的发送者
mailMessage.setFrom(from);
// 创建邮件的接收者地址,并设置到邮件消息中
InternetAddress[] receiverAddress = new InternetAddress[mailInfo.getToAddressList().size()];
for (int i = 0; i < mailInfo.getToAddressList().size(); i++) {
receiverAddress[i] = new InternetAddress(mailInfo.getToAddressList().get(i));
}
mailMessage.setRecipients(Message.RecipientType.TO, receiverAddress);
// 设置邮件消息的主题
mailMessage.setSubject(mailInfo.getSubject());
// 设置邮件消息发送的时间
mailMessage.setSentDate(new Date());
return mailMessage;
}
}
⑥ 验证邮件发送
//测试方法
public static void main(String[] args){
MailSenderInfo mailSenderInfo = new MailSenderInfo();
mailSenderInfo.setMailServerHost("smtp.163.com");
mailSenderInfo.setFromAddress("[email protected]");
mailSenderInfo.setValidate(true);
mailSenderInfo.setUserName("[email protected]");
mailSenderInfo.setPassword("XXXXXXXXXX");
List toAddressList = new ArrayList<>();
toAddressList.add("[email protected]");
mailSenderInfo.setToAddressList(toAddressList);
mailSenderInfo.setSubject("测试邮件");
mailSenderInfo.setContent("测试测试测试测试测试...");
mailSenderInfo.setAttachFileNames(Arrays.asList("C:\\Users\\changkong\\Desktop\\test.sql"));
try {
Email.sendTextMail(mailSenderInfo);
} catch (Exception e) {
e.printStackTrace();
}
}