在用戶註冊及忘記密碼功能中需要使用發送驗證碼到郵箱,spring-boot中只需要在properties文件添加相關配置就能實現發送郵件的功能。
在yml文件中添加如下配置
spring:
email:
#SMTP server host,這裏我使用的是阿里雲SMTP服務器
host: smtp.qiye.aliyun.com
# Login user of the SMTP server
username: test@aaa.com
# Login password of the SMTP server
password: 123456
# Protocol used by the SMTP server
protocol: smtp
default-encoding: utf-8
properties:
mail:
smtp:
starttls:
enable: false
auth: true
socketFactory:
class: javax.net.ssl.SSLSocketFactory
port: 465
2.使用JavaMailSender發送郵件
public abstract class AbstractEmailHandler {
Logger logger= LogManager.getLogger(EmailHandler.class);
@Autowired
private JavaMailSender mailSender;
@Autowired
private TemplateEngine templateEngine;
/**
* 發送 html 格式郵件
* @param from 發件人郵箱
* @param to 收件人郵箱
* @param subject 主題
* @param content 內容
*/
public void sendHtmlEmail(String from,String to,String subject,String content) {
if (logger.isInfoEnabled()) {
logger.info("start send html email ");
}
MimeMessage mimeMessage=mailSender.createMimeMessage();
try {
MimeMessageHelper messageHelper=new MimeMessageHelper(mimeMessage,true);
messageHelper.setFrom(from);
messageHelper.setTo(to);
messageHelper.setSubject(subject);
messageHelper.setText(content,true);
ClassPathResource logoImage=new ClassPathResource("templates/images/logo.png");
messageHelper.addInline("logoImage",logoImage);
mailSender.send(mimeMessage);
if (logger.isInfoEnabled()) {
logger.info("html email send success");
}
} catch (Exception e) {
logger.error("發送驗證碼郵件出錯",e);
throw new BusinessException(ResponseStatusCode.REQUEST_BUSINESS_ERROR.getCode(),"驗證碼郵件發送失敗");
}
}
/**
* 發送HTML郵件
* @param fromEmail 發送者郵箱地址
* @param toEmail 收件人郵箱地址
* @param subject 主題
* @param templateName 模板名稱
* @param contextParams 模板上下文變量
*/
public void sendHtmlEmail(String fromEmail, String toEmail, String subject, String templateName, Map<String,Object> contextParams) {
// 創建html模板上下文對象
Context context = new Context(Locale.CHINESE);
if (contextParams!= null && !contextParams.isEmpty()) {
context.setVariables(contextParams);
}
// 處理模板內容
String emailContent = templateEngine.process(templateName, context);
// 發送html郵件
sendHtmlEmail(fromEmail, toEmail, subject, emailContent);
}
/**
* 發送文字郵件
* @param fromEmail
* @param toEmail
* @param subject
* @param content
*/
public void sendCharacterEmail(String fromEmail,String toEmail,String subject,String content) {
if (logger.isInfoEnabled()) {
logger.info("start send character email ");
}
MimeMessage mimeMessage=mailSender.createMimeMessage();
MimeMessageHelper messageHelper= null;
try {
messageHelper = new MimeMessageHelper(mimeMessage,true);
messageHelper.setFrom(fromEmail);
messageHelper.setTo(toEmail);
messageHelper.setSubject(subject);
messageHelper.setText(content,false);
mailSender.send(mimeMessage);
if (logger.isInfoEnabled()) {
logger.info("charater email send success");
}
} catch (MessagingException e) {
logger.error("發送郵件出錯",e);
throw new BusinessException(ResponseStatusCode.REQUEST_BUSINESS_ERROR.getCode(),"郵件發送失敗");
}
}
}