记录一次使用基于SpringBoot来设置发送邮件的服务
org.springframework.boot
spring-boot-starter-mail
${springboot.version}
#发送邮件配置相关
# 配置邮件服务器的地址 smtp.qq.com
spring.mail.host=smtp.qq.com
# 配置邮件服务器的端口(465或587)
spring.mail.port=465
# 配置用户的账号
spring.mail.username=xxxxx@qq.com
# 配置用户的密码
spring.mail.password=填入授权码
# 配置默认编码
spring.mail.default-encoding=UTF-8
# SSL 连接配置
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
# 开启 debug,这样方便开发者查看邮件发送日志
spring.mail.properties.mail.debug=true
#邮件配置结束
Service层:注入JavaMailSender对象,利用MimeMessageHelper对象来设置要发送的邮件,最后调用JavaMailSender的send()方法进行发送
private void sendEmailCode(String toEmail, String code) {
try {
MimeMessage message = javaMailSender.createMimeMessage();
//MimeMessageHelper用来简化对MineMessage的设置
MimeMessageHelper helper = new MimeMessageHelper(message, true);
//邮件发件人
helper.setFrom(appConfig.getSendUserName());
//邮件收件人 1或多个
helper.setTo(toEmail);
SysSettingsDto sysSettingsDto = redisComponent.getSysSettingsDto();
//邮件主题
helper.setSubject(sysSettingsDto.getRegisterEmailTitle());
//邮件内容
helper.setText(String.format(sysSettingsDto.getRegisterEmailContent(), code));
//邮件发送时间
helper.setSentDate(new Date());
javaMailSender.send(message);
} catch (Exception e) {
logger.error("邮件发送失败", e);
throw new BusinessException("邮件发送失败");
}
}