Springboot集成Email
1、Pom文件:
<!-- email config --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
2、配置文件
#email module spring.mail.host=smtp.qq.com spring.mail.protocol=smtp spring.mail.default-encoding=UTF-8 spring.mail.username=xxx@qq.com spring.mail.password=xxx spring.mail.test-connection=true spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true
3、发送邮件实体
@Data public class ToEmail implements Serializable { private static final long serialVersionUID = 1L; /** * 邮件接收方,可多人 */ private String[] tos; /** * 邮件主题 */ private String subject; /** * 邮件内容 */ private String content; /** * 邮件附件 */ private File[] files; public ToEmail(String[] tos, String subject, String content, File[] files) { this.tos = tos; this.subject = subject; this.content = content; this.files = files; } }
4、接口类
public interface EmailService{ void sendEmail(ToEmail toEmail); }
5、接口实现类
@Service @Slf4j public class EmailServiceImpl implements EmailService { @Resource private JavaMailSender mailSender; @Value("${spring.mail.username}") private String from; @Override public void sendEmail(ToEmail toEmail) { //创建一个MINE消息 MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); //谁发 helper.setFrom(from); //谁接收 helper.setTo(toEmail.getTos()); //邮件主题 helper.setSubject(toEmail.getSubject()); //邮件内容 true 表示带有附件或html helper.setText(toEmail.getContent(), true); //邮件附件 if (toEmail.getFiles() != null && toEmail.getFiles().length > 0) { for (int i = 0; i <toEmail.getFiles().length ; i++) { File file = toEmail.getFiles()[i]; FileSystemResource fileSystemResource = new FileSystemResource(file); String filename = fileSystemResource.getFilename(); //添加附件 helper.addAttachment(filename, file); } } mailSender.send(message); log.info("邮件发送成功"); } catch (MessagingException e) { log.error("邮件发送失败|",e); } } }
6、测试类
@Api(tags = "测试管理") @RestController @RequestMapping("/test") public class TestController { @Resource private EmailService emailService; @ApiOperation(value = "测试发送邮件") @GetMapping(path = "/testSendEmail") public Response testSendEmail() { return new ResponseCallBack() { @Override public void execute(ResponseCriteria criteria, Object... obj) { String[] tos = {"123@qq.com"}; String subject = "测试标题"; String content = "测试内容"; File[] files = { new File("E:\\home\\test\\xxx.pdf"), new File("E:\\home\\test\\xxx.pdf") }; emailService.sendEmail(new ToEmail(tos, subject, content, files)); criteria.addSingleResult(true); } }.sendRequest(); } }
个人交流Q:772182648
以上是本人自己总结,并且在项目中实际用到的。新手一枚,不喜勿喷!