pom文件添加依赖
<!--邮件依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
application.properties配置文件配置
# MailProperties
#添加邮箱的配置。**注意!**使用qq邮箱时,密码是qq邮箱开启POP/SMTP后的授权码,不是邮箱本身的密码
# MailProperties
spring.mail.host=smtp.qq.com
spring.mail.port=465
spring.mail.username=xxxxxx@qq.com
spring.mail.password=我是qq邮箱授权码
#加密的协议
spring.mail.protocol=smtps
#使用ssl安全连接
spring.mail.properties.mail.smtp.ssl.enable=true
编写发邮件的工具类
util.MailCLient
@Component
public class MailClient {
//记录日志
private static final Logger logger = LoggerFactory.getLogger(MailClient.class);
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from; //发件人
//发送邮件,参数:发给谁,主题,内容
public void sendMail(String to, String subject, String content) {
try {
//模板
MimeMessage message = mailSender.createMimeMessage();
//使用帮助类构建详细的message内容
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setFrom(from);//发件人
helper.setTo(to); //收件人
helper.setSubject(subject); //主题
helper.setText(content, true);//内容,支持html文本
mailSender.send(helper.getMimeMessage());//发送
} catch (MessagingException e) {
logger.error("发送邮件失败:" + e.getMessage());
}
}
}
编写测试类
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class MailTests {
@Autowired
private MailClient mailClient;
@Autowired
private TemplateEngine templateEngine;
@Test
public void testTextMail() {
mailClient.sendMail("xxxxxx@qqcom", "TEST", "Welcome.");
}
@Test
public void testHtmlMail() {
Context context = new Context();
context.setVariable("username", "sunday");
String content = templateEngine.process("/mail/demo", context);
System.out.println(content);
mailClient.sendMail("xxxxxx@qq.com", "HTML", content);
}
}