Spring Boot实现邮件发送服务
邮件多人同时发送
引入pom坐标
<!--email -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
yml配置文件
spring
## 邮件配置
mail:
# 邮件服务地址
host: smtp.exmail.qq.com
# 端口,可不写默认
port: 465
# 编码格式
default-encoding: utf-8
# 用户名
username: blog@songzixian.com
# 授权码,就是我们刚才准备工作获取的代码
password: 123456
# 其它参数
properties:
mail:
smtp:
# 如果是用 SSL 方式,需要配置如下属性,使用qq邮箱的话需要开启
ssl:
enable: true
required: true
# 邮件接收时间的限制,单位毫秒
timeout: 10000
# 连接时间的限制,单位毫秒
connectiontimeout: 10000
# 邮件发送时间的限制,单位毫秒
writetimeout: 10000
ResponseResult通用数据的传输对象工具类https://songzixian.com/javatuils/1084.html
创建接口
/**
* <p>
* Description:
* </p>
*
* @author songzixian
* @version v1.0.0
* @create 2021-01-11 17:20
* @see com.greatdata.service
*/
public interface MailService {
public JavaMailSender sendMail(List<String> recipients, String tile, String centent);
}
//创建实现类
/**
* <p>
* Description: 邮件发送服务
* </p>
*
* @author songzixian
* @version v1.0.0
* @create 2021-01-11 17:20
* @see com.greatdata.service.impl
*/
@Slf4j
@Service
public class MailServiceImpl implements MailService {
@Autowired
private JavaMailSender javaMailSender;
/**
* 邮件发送者
*/
private static final String SENDER = "blog@songzixian.com";
/**
* description 邮件发送
* @params []
* @return {@link ResponseResult}
*/
@Override
public JavaMailSender sendMail(List<String> recipients, String tile, String centent) {
//创建数组
String[] strings = new String[recipients.size()];
//把集合转为数组
recipients.toArray(strings);
//创建消息
MimeMessage message = javaMailSender.createMimeMessage();
try {
//true表示需要创建一个multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
// 不带昵称
helper.setFrom(SENDER);
// 自定义昵称
// helper.setFrom("定时服务系统"+'<'+SENDER+'>');
//多人发送邮件
helper.setTo(strings);
//邮件标题
helper.setSubject(tile);
//邮件内容,支持html
helper.setText(centent, true);
JavaMailSender javaMailSender = this.javaMailSender;
javaMailSender.send(message);
} catch (MessagingException e) {
log.error("发送MimeMessge时发生异常,日志是:" + e);
return javaMailSender;
}
return javaMailSender;
}
}
控制层
/**
* <p>
* Description:
* </p>
*
* @author songzixian
* @version v1.0.0
* @create 2021-01-12 10:09
* @see com.greatdata.controller
*/
@Log4j2
@RestController
public class MailController {
@Autowired
private MailService mailService;
/**
* description 邮件发送服务
* @params [recipients 收件人, tile 邮件标题, centent 邮件内容]
* @return {@link ResponseResult}
*/
@RequestMapping("sendMail")
public ResponseResult sendMail(@RequestParam List<String> recipients, String tile, String centent){
if (recipients==null||recipients.size()==0){
return new ResponseResult(ResponseCode.FAILURE,"邮件接收人不能为空!");
}
try {
mailService.sendMail(recipients,tile,centent);
}catch (Exception e){
return new ResponseResult(ResponseCode.FAILURE,"邮件发送失败");
}
return new ResponseResult(ResponseCode.SUCCESS,"邮件发送成功");
}
}
测试地址:http://localhost:8080/sendMail?recipients=me@songzixian.com,admin@52xbc.cn&tile=邮件标题¢ent=邮件内容,支持html