- yml配置文件
spring:
mail:
host: smtp.qq.com
port: 587
username: 发件人的QQ邮箱
password: QQ邮箱里设置-》账户-》开启POP3/SMTP服务-》取得的码
protocol: smtp
default-encoding: UTF-8
properties:
mail.smtp.auth: true
mail.smtp.starttls.enable: true
mail.smtp.starttls.required: true
mail.smtp.socketFactory.port: 465
mail.smtp.socketFactory.class: javax.net.ssl.SSLSocketFactory
mail.smtp.socketFactory.fallback: false
thymeleaf:
cache: false
prefix: classpath:/templates/
check-template-location: true
suffix: .html
encoding: UTF-8
servlet:
content-type: text/html
mode: HTML
- 代码
1 导入jar包
implementation 'org.springframework.boot:spring-boot-starter-mail'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
2 创建一个发送邮件的类,将以下两个注入,并写一个得到数据的函数
@Resource
private JavaMailSender mailSender;
private final TemplateEngine templateEngine;
private MimeMessage getMimeMessage(final EmailBody body, final String template, final String toEmail
) throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setFrom(emailFrom);
mimeMessageHelper.setTo(toEmail);
mimeMessageHelper.setSubject(body.getTitle());
mimeMessageHelper.setText(templateEngine.process(template, body.getContext()), true);
return mimeMessage;
}
3 创建一个荷载数据的类,其中email.title为邮件的抬头,email.context为荷载,context.setVariable(“expire”, time);的expire为页面上要展示的文本的名字。
@AllArgsConstructor
@NoArgsConstructor
@Data
public class EmailBody {
@JsonIgnore
private static final String DEFAULT_TITLE = "密码重置";
private String title;
private Context context;
public static EmailBody build(final int random, final Long time) {
EmailBody email = new EmailBody();
Context context = new Context();
context.setVariable("random", random);
context.setVariable("expire", time);
email.title = DEFAULT_TITLE;
email.context = context;
return email;
}
}
4 发送,可以用线程池发送
public void notifyPasswordReset(final MimeMessage mimeMessage) throws MessagingException {
mailSender.send(mimeMessage));
}
}
|