1,maven引用
org.springframework.boot spring-boot-starter-mail
2,application.yml配置
#发送邮箱位置
spring:
#发送邮箱位置
mail:
host: smtp.qq.com
#启动调试开关
debug: true
#发送者邮箱
username: xxx@qq.com
#QQ邮箱授权码
password: xxx
protocol: smtp
default-encoding: UTF-8
properties:
mail:
smtp:
#设置认证开关
auth: true
#设置发送延时
timeout: 0
ssl:
#一定要开启ssl,不然会503 验证失败的
enable: true
starttls:
enable: true
required: true
jndi-name: mail/Session
3,发送邮件工具类
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Slf4j
@Component
public class SendMailUtil {
@Value("${spring.mail.username}")
private String username;
@Resource
private JavaMailSenderImpl javaMailSender;
// 维护一个本类的静态变量
public static SendMailUtil sendMailUtil;
// 初始化的时候,将本类中的javaMailSender赋值给静态的本类变量
@PostConstruct
public void init() {
sendMailUtil = this;
sendMailUtil.javaMailSender = this.javaMailSender;
sendMailUtil.username = this.username;
}
public static boolean sendMail(String to, String subject, String context,String dirPath,String fileName) {
MimeMessage message = sendMailUtil.javaMailSender.createMimeMessage();
MimeMessageHelper helper = null;
try {
helper = new MimeMessageHelper(message, true);
helper.setSubject(subject);
// 发送html格式内容
helper.setText(context, true);
//接收人
helper.setTo(to);
//发送人
helper.setFrom(sendMailUtil.username);
//添加附件,多个附件循环就行了
File file = new File(dirPath);
File[] files = file.listFiles();
//路径下的文件需要存在
if (files.length != 0) {
helper.addAttachment(fileName, new File(dirPath + fileName));
}
sendMailUtil.javaMailSender.send(message);
return true;
} catch (MessagingException e) {
log.error(e.getMessage());
return false;
} catch (Exception ex) {
log.error(ex.getMessage());
return false;
}
}
}
遇到的问题:
1,邮件上传附件名称很长,会出现显示不完全的情况
解决:启动类加上以下代码
//解决发送邮件文件名过长,文件乱码或缺失导致格式不正确(spring默认将文件名长度大于60时,会进行截取,所以需要关闭此设置)
System.getProperties().setProperty("mail.mime.splitlongparameters","false");
2,如果需要费发送超前时间的邮件,会出现没有权限的问题
解决:application.yml修改该配置
#设置认证开关 auth: false
3,邮箱授权码获取步骤:
(1)进入QQ邮箱,设置 => 账户
(2)点击开启,然后再点击温馨提示的生成授权码进行获取



