javascript
SpringBoot —— 实现邮件、短信的发送功能
文章目錄
- 前言
- 一、開啟服務
- 1.POP3和SMTP協(xié)議
- 2.獲取授權碼
- 二、使用步驟
- 1.環(huán)境配置
- 2.代碼編寫
- 3.郵件發(fā)送測試
- 4.短信發(fā)送
前言
SpringBoot系列Demo代碼,實現(xiàn)郵件和短信的發(fā)送。
一、開啟服務
1.POP3和SMTP協(xié)議
Spring框架為使用JavaMailSender接口發(fā)送電子郵件提供了一個簡單的抽象,Spring Boot為它提供了自動配置以及啟動模塊。
在使用Spring Boot發(fā)送郵件之前,要開啟POP3和SMTP協(xié)議,需要獲得郵件服務器的授權碼
SMTP 協(xié)議全稱為 Simple Mail Transfer Protocol,譯作簡單郵件傳輸協(xié)議,它定義了郵件客戶端軟件與 SMTP 服務器之間,以及 SMTP 服務器與 SMTP 服務器之間的通信規(guī)則。
POP3 協(xié)議全稱為 Post Office Protocol ,譯作郵局協(xié)議,它定義了郵件客戶端與 POP3 服務器之間的通信規(guī)則
2.獲取授權碼
以QQ郵箱為例:
開啟服務之后,會獲得一個授權碼:成功開啟POP3/SMTP服務,在第三方客戶端登錄時,密碼框請輸入以下授權碼:
二、使用步驟
1.環(huán)境配置
引入依賴
<!-- springboot 郵件mail --> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId> </dependency> <!--Thymeleaf--> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>application.yml
spring:# 數據源datasource:url: jdbc:mysql://localhost:3306/local_develop?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8username: rootpassword: rootdriver-class-name: com.mysql.jdbc.Driverprofiles:active: @spring.profiles.active@# 郵件mail:default-encoding: utf-8# 配置 SMTP 服務器地址host: smtp.qq.com#發(fā)送方郵件名username: #授權碼password: # thymeleaf模板格式thymeleaf:cache: falseencoding: UTF-8mode: HTMLservlet:content-type: text/htmlprefix: classpath:/templates/suffix: .html2.代碼編寫
SendMail.java
@Service public class SendMail {private final static Logger LOGGER = LoggerFactory.getLogger(SendMail.class);@Autowiredprivate JavaMailSender mailSender;@Value("${spring.mail.username}")private String sendFrom;/*** 發(fā)送簡單郵件** @param sendTo 接收人* @param subject 郵件主題* @param text 郵件內容*/public void sendSimpleMail(String sendTo, String subject, String text) {SimpleMailMessage message = new SimpleMailMessage();message.setFrom(sendFrom);message.setTo(sendTo);message.setSubject(subject);message.setText(text);mailSender.send(message);}/*** 發(fā)送HTML格式的郵件,并可以添加附件** @param sendTo 接收人* @param subject 郵件主題* @param content 郵件內容(html)* @param files 附件* @throws MessagingException*/public void sendHtmlMail(String sendTo, String subject, String content, List<File> files) {MimeMessage message = mailSender.createMimeMessage();// true表示需要創(chuàng)建一個multipart messagetry {MimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setFrom(sendFrom);helper.setTo(sendTo);helper.setSubject(subject);helper.setText(content, true);//添加附件for (File file : files) {helper.addAttachment(file.getName(), new FileSystemResource(file));}mailSender.send(message);} catch (MessagingException e) {LOGGER.warn("郵件發(fā)送出錯:{}", e);}} }SendMailController.java
@Api(value = "郵件發(fā)送接口", tags = "郵件發(fā)送接口") @RestController @RequestMapping("/index") public class SendMailController {@Autowiredprivate SendMail sendMail;@Autowiredprivate TemplateEngine templateEngine;@ApiOperation(value = "發(fā)送簡單郵件", notes = "發(fā)送簡單郵件")@ApiImplicitParams({@ApiImplicitParam(name = "sendTo", required = true, value = "接收人"),@ApiImplicitParam(name = "subject", required = false, value = "郵件主題"),@ApiImplicitParam(name = "text", required = false, value = "郵件內容"),})@GetMapping("/sendSimpleMail")public ApiResponse sendSimpleMail(@RequestParam String sendTo,@RequestParam(required = false) String subject,@RequestParam(required = false) String text) {sendMail.sendSimpleMail(sendTo, subject, text);return ApiResponse.ok();}@ApiOperation(value = "發(fā)送HTML格式的郵件", notes = "使用Thymeleaf模板發(fā)送郵件")@ApiImplicitParams({@ApiImplicitParam(name = "sendTo", required = true, value = "接收人"),@ApiImplicitParam(name = "subject", required = false, value = "郵件主題"),@ApiImplicitParam(name = "content", required = true, value = "郵件模板"),})@GetMapping("/sendHtmlMail")public ApiResponse sendHtmlMail(@RequestParam String sendTo,@RequestParam(required = false) String subject,@RequestParam String content) {Context context = new Context();context.setVariable("username", "xx");context.setVariable("num", "007");// 模板String template = "mail/" + content;List<File> files = new ArrayList<>();sendMail.sendHtmlMail(sendTo, subject, templateEngine.process(template, context), files);return ApiResponse.ok();}}mail.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head><meta charset="UTF-8"><title>Title</title> </head> <body> <p>hello 歡迎加入 榮華富貴 大家庭,您的入職信息如下:</p> <table border="1"><tr><td>姓名</td><td th:text="${username}"></td></tr><tr><td>工號</td><td th:text="${num}"></td></tr> </table> <div style="color: #ff1a0e">加油加油</div> <div style="color: #ff1a0e">努力努力!</div> <div style="color: #ff1a0e">今天睡地板,明天當老板!</div> </body> </html>3.郵件發(fā)送測試
啟動項目,打開http://localhost:8080/doc.html
調試接口,效果如下:
4.短信發(fā)送
短信發(fā)送通過調用API實現(xiàn),具體參考:https://blog.csdn.net/qq_34383510/article/details/115939788
本文參考:http://springboot.javaboy.org/2019/0717/springboot-mail
? 上一章:SpringBoot —— 整合Logback,輸出日志到文件
? 下一章:SpringBoot —— 多線程定時任務的實現(xiàn)(注解配置、task:annotation-driven配置)
總結
以上是生活随笔為你收集整理的SpringBoot —— 实现邮件、短信的发送功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab两组数据的相关度,怎么分析两
- 下一篇: JavaScript运筹帷幄,掌控全局