springboot 整合邮件发送功能
springboot 整合邮件发送功能
pom依赖
代码实现
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Properties;
public class Email {
/**
* 发送邮件
*/
private static Boolean sendMail() throws Exception {
try {
// 获取系统属性
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", "smtp.163.com");// 设置邮件服务器
properties.setProperty("mail.smtp.auth", "true");// 打开认证
properties.setProperty("mail.smtp.port", "25"); //设置端口
properties.setProperty("mail.debug", "false"); // 是否打印日志
properties.setProperty("mail.smtp.connectiontimeout", "15000");//SMTP服务器连接超时时间
properties.setProperty("mail.smtp.timeout", "60000");//发送邮件超时时间
//设置密码需要实现抽象类Authenticator 重写 getPasswordAuthentication方法 原方法返回null
// AuthenticatorCheck authenticatorCheck = new AuthenticatorCheck("gaoph_dcits@163.com", "VKGHGACJBXFMURWZ");
Authenticator authenticatorCheck = new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("gaoph_dcits@163.com", "VKGHGACJBXFMURWZ");
}
};
Session session = Session.getDefaultInstance(properties, authenticatorCheck);
MimeMessage message = new MimeMessage(session);
MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "UTF-8");
messageHelper.setFrom(new InternetAddress("gaoph_dcits@163.com", "央行流动性邮件发送服务", "UTF-8"));
messageHelper.setTo(new String[]{"m18110024862@163.com"});
messageHelper.setSubject("提醒");
messageHelper.setText("我去,hahh......" +
"
这是红色
"设置span内字体大小为24px" +
"