pom 文件
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.5</version>
</dependency>
1,工具类
@Data
public class EmailConfigModel {
/**
* 启用, 0:启用, 1:弃用。
*/
private Integer enable;
/**
* 邮箱。
*/
private String emailBox;
/**
* 邮箱密码。
*/
private String passWord;
/**
* 端口。
*/
private String port;
/**
* 邮件服务器地址。
*/
private String serverUrl;
/**
* ssl启用, 0:启用, 1:弃用。
*/
private Integer enSsl;
}
2,附件
@Data
public class AFile {
/**
* 文件名称
*/
private String name;
/**
* 文件连接
*/
private String url;
}
3,工具类
@Log4j
public class EmailUtil {
private EmailUtil() {
}
private static final String AINAME = "AI";
private static final int SOCKET_TIMEOUT_MS = 10000;
static {
System.setProperty("mail.mime.splitlongparameters", "false");
System.setProperty("mail.mime.charset", "utf-8");
}
public static synchronized void deliverWithMime(EmailConfigModel emailConfigModel,
String subject,
String msg,
String toMail,
List<AFile> attachmentList,
List<AFile> detailPicList)
throws MessagingException, GeneralSecurityException {
Properties prop = new Properties();
prop.setProperty("mail.host", emailConfigModel.getServerUrl());
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.port", String.valueOf(emailConfigModel.getPort()));
prop.setProperty("mail.mime.splitlongparameters", "false");
prop.setProperty("mail.smtp.auth", "true");
if (emailConfigModel.getEnSsl() == 0) {
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
}
//使用JavaMail发送邮件的5个步骤
//1、创建session
Session session = Session.getInstance(prop, new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(emailConfigModel.getEmailBox(), emailConfigModel.getPassWord()); //发件人邮件用户名、密码
}
});
//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
session.setDebug(false);
//2、通过session得到transport对象
Transport ts = session.getTransport();
//3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。
ts.connect(emailConfigModel.getEmailBox(), emailConfigModel.getPassWord());
//4、创建邮件
MimeMessage message = new MimeMessage(session);
//4.1、设置邮件的基本信息
//4.2、发件人
String nick = "";
try {
nick = MimeUtility.encodeText("ai");
} catch (UnsupportedEncodingException e) {
System.out.println("编码失败:" + "ai" + e);
}
message.setFrom(new InternetAddress(nick + "<" + emailConfigModel.getEmailBox() + ">"));
//4.3、收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(toMail));
//4.4、邮件标题
message.setSubject(subject);
//4.5、创建邮件附件
MimeMultipart mp = new MimeMultipart();
FileDataSource filedatasource;
MimeBodyPart filePart;
List<AFile> attachments = new ArrayList<>();
if (attachmentList != null) {
attachments.addAll(attachmentList);
}
if (detailPicList != null) {
attachments.addAll(detailPicList);
}
for (AFile attachment : attachments) {
File file = new File(attachment.getUrl());
if (file.exists()) {
filePart = new MimeBodyPart();
filedatasource = new FileDataSource(file);
filePart.setDataHandler(new DataHandler(filedatasource));
try {
filePart.setFileName(MimeUtility.encodeText(attachment.getName()));
} catch (Exception e) {
log.error("设置文件名失败:" + file.getName(), e);
}
mp.addBodyPart(filePart);
}
}
//4.6、写入文本内容
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(msg, "text/html; charset=utf-8");
mp.addBodyPart(htmlPart);
//4.7、组合内容
message.setContent(mp);
message.saveChanges();
//5、发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}
private static Email buildEmailInstance(EmailConfigModel emailConfigModel) throws EmailException {
Email emailInstance = new SimpleEmail();
emailInstance.setDebug(false);
emailInstance.setHostName(emailConfigModel.getServerUrl());
if (emailConfigModel.getEnSsl() == 0) {
//前端传值错误,当ssl = 0时是打开ssl
emailInstance.setSslSmtpPort(emailConfigModel.getPort());
} else {
emailInstance.setSmtpPort(Integer.parseInt(emailConfigModel.getPort()));
}
emailInstance.setAuthenticator(
new DefaultAuthenticator(emailConfigModel.getEmailBox(), emailConfigModel.getPassWord()));
emailInstance.setSSLOnConnect(emailConfigModel.getEnSsl() == 0);
emailInstance.setFrom(emailConfigModel.getEmailBox(), AINAME);
emailInstance.setSocketTimeout(SOCKET_TIMEOUT_MS);
return emailInstance;
}
public static void sendSimpleEmail(EmailConfigModel emailConfigModel, String subject, String msg, String toMail)
throws EmailException {
String newMsg = msg.replace("#$]", "\r\n");
Email email = buildEmailInstance(emailConfigModel);
email.setSubject(subject).addTo(toMail).setMsg(newMsg).send();
}
public static void sendSimpleEmailByHtml(EmailConfigModel emailConfigModel, String subject, String msg, String toMail)
throws EmailException {
Email email = buildEmailInstance(emailConfigModel);
email.setContent(msg, "text/html;charset=utf-8");
email.setSubject(subject).addTo(toMail).send();
}
public static void main(String[] args) throws GeneralSecurityException, MessagingException {
EmailConfigModel emailConfigModel = new EmailConfigModel();
emailConfigModel.setServerUrl("smtp.163.com");
emailConfigModel.setEmailBox("xxxxxx@163.com");
emailConfigModel.setPort("25");
emailConfigModel.setPassWord("安全码");
emailConfigModel.setEnSsl(1);
emailConfigModel.setEnable(0);
EmailUtil.deliverWithMime(emailConfigModel, "测试邮箱", "你好,请忽略", "xxxxx@qq.com", null, null);
}
}