项目中遇到的一个发送邮件的一个需求,特此记录一下!其中mailUserName是邮箱名称,mailPassword是开启pop3/smtp时的验证码
package com.ruoyi.common.utils;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Properties;
@Slf4j
public class EmailUtils {
/**
* 发送邮件
*
* @param emailSubject 邮件主题
* @param emailContent 邮件内容
* @param addresseeList 邮件收件人地址List
*/
public static void mailSend(String emailSubject, String emailContent, List<String> addresseeList) {
//发件人邮箱 支持 139(移动)、163、qq
String mailUserName = RuoYiConfig.getMailUserName();
//开启pop3/smtp时的验证码
String mailPassword = RuoYiConfig.getMailPassword();
if (StringUtils.isEmpty(mailPassword) || StringUtils.isEmpty(mailUserName)) {
throw new ServiceException("没有配置邮箱或邮箱smtp验证码!");
}
String smtpHost = "";
if (mailUserName.contains("139")) {//移动 SMTP服务器
smtpHost = "smtp.139.com";
} else if (mailUserName.contains("qq")) {//腾讯 SMTP服务器
smtpHost = "smtp.qq.com";
} else if (mailUserName.contains("163")) {//网易 SMTP服务器
smtpHost = "smtp.163.com";
} else {
throw new ServiceException("没有适配SMTP服务器,请重新填写发件人邮箱:只支持 139(移动)、163、qq 邮箱!");
}
// 配置邮件服务器
Properties props = new Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "25");
// 创建Session对象
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(mailUserName, mailPassword);
}
});
try {
// 创建Message对象
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(mailUserName));
for (int i = 0; i < addresseeList.size(); i++) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(addresseeList.get(i)));
}
message.setSubject(emailSubject);
message.setText(emailContent);
// 发送邮件
Transport.send(message);
log.info("发送邮件成功:已向" + addresseeList + "发送邮件");
} catch (MessagingException e) {
log.error("发送邮件失败:" + e.getMessage());
}
}
}