package com.mail;
import com.sun.mail.util.MailSSLSocketFactory;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Properties;
/**
* 发邮件工具类
*/
@Component
public class MailUtils {
@Value("${mail.user}")
private String mailUser; // 发件人邮箱地址
@Value("${mail.password}")
private String mailPassword; // 密码
/**
* 发送邮件
*
* @param to 收件人邮箱
* @param text 邮件正文
* @param title 标题
*/
public boolean sendMail(String to, String text, String title) {
try {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.setProperty("mail.transport.protocol", "smtp");
props.put("mail.host", "smtp.xx.163.com");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
// 发件人的账号
props.put("mail.user", mailUser);
//发件人的密码
props.put("mail.password", mailPassword);
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用环境属性和授权信息,创建邮件会话
Session mailSession = Session.getInstance(props, authenticator);
// 创建邮件消息
MimeMessage message = new MimeMessage(mailSession);
// 设置发件人
String username = props.getProperty("mail.user");
InternetAddress form = new InternetAddress(username);
message.setFrom(form);
// 设置收件人
InternetAddress toAddress = new InternetAddress(to);
message.setRecipient(Message.RecipientType.TO, toAddress);
// 设置邮件标题
message.setSubject(title);
// 设置邮件的内容体
message.setContent(text, "text/html;charset=UTF-8");
// 发送邮件
Transport.send(message);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
注意:需要启动SpringBoot项目启动时调用接口,或者是定时任务(定时任务的话需要开启定时任务,在SpringBoot启动类中加上@EnableScheduling否则定时任务不起效果)。我这边用的是@PostConstruct时SpringBoot起启动就会调用发送。
@Autowired
privatee MailUtil mailUtil;
@PostConstruct
public void test(){
mailUtil.sendMail(xx,xx,xx);
}