一:引入依赖
<!--mail-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
二:编写工具类
package com.ambul.core.config;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;
/**
* @author lrx
* @description: TODO 企业邮箱工具类
* @date 2022/6/2 18:08
*/
public class SendMail {
private static Properties prop = null;
private static MimeMessage mimeMessage;
final static String E_ACCOUNT = "xx企业邮箱账号";
final static String E_PAW = "密码";
private static void init(){
try {
prop = new Properties();
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.host", "smtp.exmail.qq.com"); //服务器
prop.setProperty("mail.smtp.port", "465"); //端口
prop.setProperty("mail.smtp.auth", "true"); //使用smtp身份验证
//使用SSL,企业邮箱必需!
//开启安全协议
MailSSLSocketFactory sf = null;
try {
sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
} catch (GeneralSecurityException e1) {
e1.printStackTrace();
}
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
//
//获取Session对象
Session session = Session.getDefaultInstance(prop,new Authenticator() {
//此访求返回用户和密码的对象
@Override
protected PasswordAuthentication getPasswordAuthentication() {
PasswordAuthentication pa = new PasswordAuthentication(E_ACCOUNT, E_PAW);
return pa;
}
});
//设置session的调试模式,发布时取消
//session.setDebug(true);
mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress(E_ACCOUNT,E_ACCOUNT));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 发送邮件
*/
public static void mailSend(String recEmail,String subject,String text){
try {
if(prop == null){
init();
}
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(recEmail));
mimeMessage.setSubject(subject); //设置主题
mimeMessage.setSentDate(new Date());
mimeMessage.setText(text); //设置内容
mimeMessage.saveChanges();
Transport.send(mimeMessage); //发送
} catch (Exception e) {
e.printStackTrace();
}
}
}
三:测试代码
@Test
public void test12() {
SendMail.mailSend("xx@qq.com", "异常通知", "中央缓存宕机");
}
四:邮件消息