文章目录
开启服务
以QQ邮箱为例,我们先要在邮箱中设置–账户下找到以下向并开启:
编码
邮件发送需要引入spring-boot-starter-mail
<!--引入邮件任务依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Spring Boot自动配置MailSenderAutoConfiguration
定义MailProperties内容,配置在application.yml中
spring:
# 配置邮件任务
mail:
username: 邮箱名
password: 授权码
host: smtp.qq.com
port: 465
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
socketFactory:
port: 465
class: javax.net.ssl.SSLSocketFactory
fallback: false
MailUtils工具类
自动装配JavaMailSender
public class MailUtils {
//邮件发送器
private JavaMailSenderImpl mailSender;
Logger logger = LogUtils.getInstance(MailUtils.class);
public MailUtils(JavaMailSenderImpl mailSender){
this.mailSender = mailSender;
}
/**
* 发送简单邮件
* @param title 邮件标题
* @param text 邮件内容(简单邮件不支持HTML标签)
* @param acceptEmail 接收方邮件
*/
public void sendSimpleMailMessage(String title,String text,String acceptEmail){
logger.info("开始发送简单邮件...");
logger.info("mailSender对象为:"+mailSender);
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject(title);
message.setText(text);
message.setFrom("hg2j@qq.com");
message.setTo(acceptEmail);
System.out.println(mailSender);
logger.info("message对象为:"+message);
mailSender.send(message);
}
/**
* 发送复杂邮件(支持邮件内容HTML解析)
* @param title 邮件标题
* @param text 邮件内容(简单邮件不支持HTML标签)
* @param acceptEmail 接收方邮件
* @throws MessagingException
*/
public void sentComplexMailMessage(String title,String text,String acceptEmail){
logger.info("开始发送复杂邮件...");
logger.info("mailSender对象为:"+mailSender);
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
try {
helper.setSubject(title);
helper.setText(text,true);
helper.setFrom("hg2j@qq.com");
helper.setTo(acceptEmail);
} catch (MessagingException e) {
e.printStackTrace();
}
logger.info("mimeMessage对象为:"+mimeMessage);
mailSender.send(mimeMessage);
}
public String sendCode(String email,String userName,String password){
int code = (int) ((Math.random() * 9 + 1) * 100000/*代表几位验证码*/);
logger.info("开始发送复杂邮件...");
logger.info("mailSender对象为:"+mailSender);
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
try {
helper.setSubject("邮箱验证");
helper.setText("<h1 style='color : red'>如果并非本人操作,请忽略本邮件</h1>",true);
helper.setFrom("hg2j@qq.com");
helper.setTo(email);
} catch (MessagingException e) {
e.printStackTrace();
}
logger.info("mimeMessage对象为:"+mimeMessage);
mailSender.send(mimeMessage);
return String.valueOf(code);
}
}