SpringBoot之郵件服務


springboot 郵件服務

  今天在看網上學習微服務的時候順遍看到了一些關於springboot的文章,寫的springboot拓展功能就順遍學習了一下,接下來給大家分享一下springboot封裝集成了郵件服務。

  發送郵件應該是網站的必備拓展功能之一,注冊驗證,忘記密碼或者是給用戶發送營銷信息。正常我們會用JavaMail相關api來寫發送郵件的相關代碼,但現在springboot提供了一套更簡易使用的封裝。

簡易應用

  1.gradle配置

compile('org.springframework.boot:spring-boot-starter-mail')

  2.編寫配置

  我這里用的是qq郵箱發送,使用qq郵箱必須qq郵箱中 設置 >> 賬戶 >> 把POP3/SMTP服務開啟

  

  
  如果用qq郵箱發送這里的password不是郵箱密碼,是剛才開啟POP3/SMTP服務時生成的鏈接字符

  properties返回類型是一個Map類型,properties肯定對應的是一些拓展的參數,那個smtp一定是需要開啟的

  3.編碼實現Text發送

   

   from為發送者

   to為接受者,可以理解為訂閱者,這里可以傳數組

   subject為標題

   content為內容

   編碼測試

 

   4.編碼實現HTML發送

@Override
    public void sendHtmlMail(String to, String subject, String content) { MimeMessage message = mailSender.createMimeMessage(); try { //true表示需要創建一個multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); mailSender.send(message); System.out.println("發送成功~"); } catch (MessagingException e) { e.printStackTrace(); System.out.println("發送失敗~"); } }

    HTML的發送需要借助MimeMessage,MimeMessageHelper的setTest方法提供是否開啟html的重裝方法。

  5.編碼實現發送附件

    

 @Override
    public void sendAttachmentsMail(String to, String subject, String content,String path) { MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message,true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); FileSystemResource fileSystemResource = new FileSystemResource(new File(path)); String fileName= path.substring(path.lastIndexOf(File.separator)); helper.addAttachment(fileName,fileSystemResource); mailSender.send(message); System.out.println("發送成功!"); }catch (Exception e){ e.printStackTrace(); System.out.println("發送失敗!"); } }

     可以通過多個addAttachment方法發送多個附件,File.separator是用來分隔同一個路徑字符串中的目錄

   6.編寫實現模板發送

    我們有時候收到的郵件就想一封信一樣格式非常優雅,如果我們采用上面那種方式編寫HTML字符硬性拼接的話起步很麻煩,所有對於這種需求,我們建議使用模板來處理。

    這里采用的是Thymeleaf來演示

    1.導入build.gradle

compile('org.springframework.boot:spring-boot-starter-thymeleaf')

    2.在resources/templates新建index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
請點擊下面的鏈接來驗證身份<br/>
<a href="#" th:href="@{ http://www.baidu.com/{id} }">激活賬號</a>
</body>
</html>

    3.解析模塊發送

 

@Autowired
private TemplateEngine templateEngine; @Test public void contextLoadsFour(){ Context context = new Context(); context.setVariable("id","110"); String content = templateEngine.process("index",context); mailService.sendHtmlMail("2752555817@qq.com","Hello",content); }

    process方法第一個參數對於頁面邏輯視圖名稱


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM