一. SpringBoot对邮件的发送已经高度集成, 只需少量的配置和编码即可, 首先我们来看下需要的配置. 在application.properties文件中作如下配置:
# mail 配置
spring.mail.host=smtp.163.com
spring.mail.username=xxx@163.com
spring.mail.password=
spring.mail.port=465
#设置为SSL协议
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.from=xxx@163.com
1). spring.mail.username是登录邮箱的用户名;
2). password是在163上申请发送邮件的一串权限码(见后面的截图);
3). 端口465对于http有SSL协议来说是这个端口, 而25是无SSL协议的发送端口;
4). from配置的默认发件人, 可在邮件发送的时候指定发送人进行替换
下面截图是申请权限码的地方
image.png
二. SpringBoot提供了一个发送邮件的接口(JavaMailSender), 实现类为(JavaMailSenderImpl), 首先我们先建立Service
public interface MailService {
/**
* 邮件发送动作
* @param mailVO
* @throws BusinessException
*/
void sendMail(MailVO mailVO) throws BusinessException;
}
@Service
public class MailServiceImpl implements MailService {
@Autowired
private JavaMailSenderImpl mailSender;
@Override
public void sendMail(MailVO mailVO) throws BusinessException {
checkMail(mailVO);
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom(mailVO.getFrom());
simpleMailMessage.setTo(mailVO.getTo());
simpleMailMessage.setSubject(mailVO.getSubject());
simpleMailMessage.setText(mailVO.getText());
simpleMailMessage.setSentDate(new Date());
if (!StringUtils.isEmpty(mailVO.getCc())) {
simpleMailMessage.setCc(mailVO.getCc());
}
if (!StringUtils.isEmpty(mailVO.getBcc())) {
simpleMailMessage.setBcc(mailVO.getBcc());
}
mailSender.send(simpleMailMessage);
}
private void checkMail(MailVO mailVO) throws BusinessException {
if (StringUtils.isEmpty(mailVO.getTo())) {
throw new BusinessException(30001);
}
if (StringUtils.isEmpty(mailVO.getSubject())) {
throw new BusinessException(30002);
}
if (StringUtils.isEmpty(mailVO.getText())) {
throw new BusinessException(30003);
}
if (StringUtils.isEmpty(mailVO.getFrom())) {
mailVO.setFrom(mailSender.getJavaMailProperties().getProperty("from"));
}
if (StringUtils.isEmpty(mailVO.getFrom())) {
throw new BusinessException(30004);
}
}
}
MailVO 数据类
/**
* 功能描述: 邮件发送信息封装类;
* 作者: 飞鱼课堂 飞鱼
* 时间: 2020-6-2 20:37
*/
@Data
public class MailVO {
/**
* 发送人, 如果没有, 取全局配置的发送人;
*/
private String from;
private String to; // 发送给某人
private String subject; // 主题
private String text; // 内容
private String cc; // 抄送
private String bcc; // 密送
private Date sendDate;
}
Controller类
/**
* 功能描述:
* 作者: 飞鱼课堂 飞鱼
* 时间: 2020-6-2 20:53
*/
@RestController
@RequestMapping("/api/v1/mail")
public class MailController extends BaseController {
@Autowired
private MailService mailService;
@PostMapping("/send")
public JsonData send(@RequestParam Map<String, Object> params) throws BusinessException {
MailVO mailVO = new MailVO();
// 赋值到mailVo
BeanMap beanMap = BeanMap.create(mailVO);
beanMap.putAll(params);
mailService.sendMail(mailVO);
return this.getRsDto();
}
}
网友评论