很多时候邮件发送并不是主业务必须关注的结果,比如通知类、提醒类的业务可以允许延时或者失败。这个时候可以采用异步的方式来发送邮件,加快主交易执行速度,在实际项目中可以采用MQ发送邮件相关参数,监听到消息队列之后启动发送邮件。
1、在pom.xml文件中添加SpringBoot-mail引用
<!--整合SpringBoot-mail-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--整合SpringBoot-thymeleaf模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、SpringBoot的application.properties文件中添加邮箱配置
##配置发送邮件的服务器地址、用户名、邮箱授权码、编码
spring.mail.host=smtp.qq.com
spring.mail.username=用户名(邮箱地址)
spring.mail.password=邮箱授权码
spring.mail.default-encoding=UTF-8
3、文本、HTML、附件、多个附件、图片邮件发送的简单实现代码
package com.hern.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.ArrayList;
/**
* @program: springboot-mail
* @description: MailService
* @author: 宋兆恒[email protected]
* @create: 2020-01-20 14:30
**/
@Service
public class MailService {
private final Logger logger = Log