最近有个需求,用户评论邮件通知我,然后使用 JavaMailSender
。
由于在 properties
中配置了 mail
,这里直接注入 JavaMailSender
。
问题溯源
package com.sugar.wxblog.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.internet.MimeMessage;
import java.util.Map;
/**
* 功能描述: 邮件工具箱
*
* @author 方糖
* @date 2021/11/30 20:24
*/
@Component
@EnableAsync
public class MailUtils {
@Autowired
private JavaMailSender javaMailSender;
@Autowired
private MailProperties mailProperties;
@Autowired
TemplateEngine templateEngine;
@Async
public void sendSimpleMail(String toAccount, String subject, String content) {
try {
SimpleMailMessage message = new SimpleMailMessage();
System.out.println(mailProperties);
message.setFrom(mailProperties.getUsername());
message.setTo(toAccount);
message.setSubject(subject);
message.setText(content);
javaMailSender.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
当去测试时发现,报空指针异常,MailProperties
并没有注入成功。
@Test
void contextLoads() {
new MailUtils().sendSimpleMail("sugartech@gmail.com","","");
}
问题排查
当使用 @Autowired
注入后,交由 Spring 管理,不能使用 new
对象使用,必须从 Spring 容器中获得对象。
@Autowired
MailUtils mailUtils;
@Test
void contextLoads() {
mailUtils.sendSimpleMail("xiaoheikeji@vip.qq.com","Java 邮件发送测试","null");
}