SpringBoot發送郵件總集合

原理

郵件使用場景

  • 註冊驗證
  • 網站營銷
  • 安全的最後一道防線(找回帳戶密碼)
  • 提醒、監控告警
  • 觸發機制

郵件發送原理

  • 郵件傳輸協議:SMTP協議和POP3協議
  • 內容不斷髮展:IMAP協議和Mime協議

郵件發送歷史

  • 1969年10月,世界上的第一封電子郵件
  • 1987年9月14日中國的第一封電子郵件
  • 30年發展歷史
  • Java發送郵件
  • Spring發送郵件

Spring Boot介紹

  • 約定大於配置
  • 簡單快速開發
  • 強大的生態鏈
  • Spring Boot和發送郵件

前置知識

  • 會使用Spring進行開發
  • 對Spring Boot有必定的瞭解
  • Maven、HTML、Thymeleaf
  • 理解郵件發送的基本知識

實踐

注:基礎配置->文本郵件->HTML郵件->附件郵件->圖片郵件->郵件模板->異常處理html

  • 引入相關Jar包
  • 配置郵箱參數
  • 封裝SimpleMailMessage
  • JavaMailSender進行發送

發送文本郵件

/**
 * 發送簡單文本文件
 * @param to 向誰發送
 * @param subject 郵件主題
 * @param content 郵件內容
 */
public void sendSimpleMail(String to ,String subject,String content){
    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(to);
    message.setSubject(subject);
    message.setText(content);
    message.setFrom(emailConfig.getFrom());

    //發送郵件
    mailSender.send(message);
}
@Test
public void sendSimpleMail() throws Exception {
    mailService.sendSimpleMail("1341933031@qq.com","文本郵件","這是一封文本郵件");
}

發送HTML郵件

/**
 * 發送HTML郵件
 * @param to 向誰發送
 * @param subject 郵件主題
 * @param content 郵件內容
 * @throws MessagingException
 */
public void sendHtmlMail(String to,String subject,String content) {
    log.info("發送HTML郵件開始:{},{},{}",to,subject,content);
    MimeMessage message = mailSender.createMimeMessage();

    MimeMessageHelper helper = null;
    try {
        helper = new MimeMessageHelper(message,true);
        helper.setFrom(emailConfig.getFrom());
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content,true);
        mailSender.send(message);
        log.info("發送HTML郵件成功!");
    } catch (MessagingException e) {
        log.error("發送HTML郵件失敗:",e);
    }
}
@Test
public void sendHtmlMail() throws Exception {
    String content = "<html>\n"+
            "<body\n>"+
            "<h3>hello world , 這是一封html郵件!</h3>\n"+
            "</body>\n"+
            "</html>\n";
    mailService.sendHtmlMail(to,"html郵件",content);
}

發送附件郵件

/**
 * 發送附件郵件
 * @param to 向誰發送
 * @param subject 發送主題
 * @param content 內容
 * @param filePath 文件路徑 多文件轉數組參數
 * @throws MessagingException
 */
public void sendAttachmentsMail(String to,String subject,String content,String filePath)
        throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(message,true);
    helper.setFrom(emailConfig.getFrom());
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content,true);

    FileSystemResource file = new FileSystemResource(new File(filePath));

    String fileName = file.getFilename();
    helper.addAttachment(fileName,file);
    mailSender.send(message);
}
@Test
public void sendAttachmentsMail() throws Exception {
    String filePath = "D:\\C語言\\ch7-1 讓指針再也不困擾你.docx";
    mailService.sendAttachmentsMail(to,"附件郵件","這是一封附件郵件",filePath);
}

帶圖片的郵件

/**
 * 帶圖片的郵件
 * @param to 向誰發送
 * @param subject 主題
 * @param content 內容
 * @param rscPath 圖片地址
 * @param rscId 圖片id
 * @throws MessagingException
 */
public void sendInlinResourceMail(String to,String subject,String content,
                                  String rscPath,String rscId) throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(message,true);
    helper.setFrom(emailConfig.getFrom());
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content,true);

    FileSystemResource res = new FileSystemResource(new File(rscPath));
    helper.addInline(rscId,res);
//        helper.addInline(rscId,res);多張圖片
    mailSender.send(message);
}
@Test
public void sendInlinResourceMail() throws Exception {
    String imgPath = "C:\\Users\\Administrator\\Pictures\\公司\\user.png";
    String rscId = "new001";
    String content = "<html><body>這是有圖片的郵件:<img src=\'cid:"+rscId+
            "\'></img></body></html>";
    mailService.sendInlinResourceMail(to,"圖片郵件",content,imgPath,rscId);
}

郵件模板

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>郵件模板</title>
</head>
<body>
    你好,感謝您的註冊,這是一封驗證郵件,請點擊下面的連接完成註冊,感謝您的支持。<br/>
    <a href="#" th:href="@{https://github.com/UncleCatMySelf/{id}(id=${id})}">激活帳戶</a>
</body>
</html>
@Test
    public void testTemplateMailTest() throws MessagingException {
        Context context = new Context();
        context.setVariable("id","01");

        String emailContent = templateEngine.process("emailTemplate",context);

        mailService.sendHtmlMail(to,"模板郵件",emailContent);

    }

郵件系統

  • 獨立微服務
  • 異常處理
  • 定時重試郵件
  • 異步發送

異常

  • 421 HL:ICC 該IP同時併發鏈接數過大
  • 451 Requested mail action not taken:too much fail ... 登陸失敗次數過多,被臨時禁止登陸
  • 553 authentication is required 認證失敗

效果

圖片描述


若是本文對你有所幫助,歡迎關注我的技術公衆號,或點贊,謝謝。
圖片描述java

相關文章
相關標籤/搜索