Springboot下郵件通知

       最近公司接了宜家的幾個產品,需要在原有的抽取服務添加完成後郵寄通知功能。先搞個初級版本,話不多說,上代碼:

一,引入依賴包

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-email</artifactId>
      <version>1.5</version>
    </dependency>

二,配置相關信息

email:
  yijia:                        ##  開發環境
    host: smtp.163.com
    charset: gbk
    username: 郵箱@163.com
    password: EPXXX
    templateName: yiJiaEmail
    subject: IKEA related code table update tips
    receiveMails: 接收[email protected],接收[email protected]

      如果本地測試用自己郵件,需要開下權限。

三,郵件模板

       在resources下創建templates文件夾寫需要的模板,eg:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<style type="text/css">
    body{
        margin: 0px;
    }
    table.imagetable {
        font-size:18px;
        border-width: 1px;
        border-collapse: collapse;
        margin: auto;
    }
    table.imagetable th {
        width: 350px;
        border-width: 1px;
        padding: 15px;
        border-style: solid;
        border-color: #CDC1C5;
    }
    table.imagetable td {
        /*background:#dcddc0;*/
        border-width: 1px;
        padding: 15px;
        border-style: solid;
        border-color: #CDC1C5;
        width: 350px;
        text-align: center;
    }
    .daastitle{
        /*display: inline-block;*/
        padding: 6px 15px;
        margin-bottom: 0;
        font-size: 23px;
        font-weight: normal;
        line-height: 1.42857143;
        text-align: center;
        white-space: nowrap;
        vertical-align: middle;
        background-image: none;
        border: 1px solid transparent;
        border-radius: 4px;
        color: #fff;
        background-color: #5bc0de;
        border-color: #46b8da;
    }
</style>
<head>
    <meta charset="UTF-8"/>
</head>
<body>
<div style="width: 700px;margin: auto;margin-top:50px">
    <div class="daastitle"> 抽取任務完成</div>
    <table class="imagetable">
        <tr style="background-color: #fff">
            <td>任務名稱</td>
            <td>產品編號</td>
        </tr>
        <tr style="background-color: #fff">
            <td th:text="${taskName}"></td>
            <td th:text="${productKey}"></td>
        </tr>
    </table>
</div>
</body>
</html>

四,工具類

package com.easipass.extract.util;

import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

/**
 * @program: BDP_SRVC_DAAS_EXTRACT @Package: com.easipass.extract.util @ClassName: EmailTool
 * @author: qqzhang
 * @create: 2020-05-27 15:13
 * @description: @UpdateUser: qqzhang @UpdateRemark: @UpdateDate: 2020-05-27 15:13 @Version: 1.0
 */
@Configuration
@Slf4j
public class EmailTool {
  private static TemplateEngine templateEngine;

  @Autowired
  public EmailTool(TemplateEngine templateEngine) {
    EmailTool.templateEngine = templateEngine;
  }
  // 1  字符串   2  html
  public static Map<String, Object> sendEmail(
      Map<String, Object> datamap, Map<String, Object> emailParam, String type)
      throws EmailException {
    Map<String, Object> resultMap = new HashMap();
    int successSum = 0;
    int errSum = 0;
    StringBuffer errEmails = new StringBuffer();
    String templateName = (String) emailParam.get("templateName");
    String[] receiveMails = (String[]) emailParam.get("receiveMails");
    String subject = (String) emailParam.get("subject");
    String context = null;
    if ("1".equals(type)) {
      context = (String) datamap.get("context");
    } else if ("2".equals(type)) {
      context = getContext(datamap, templateName);
    } else {
      log.error("#####  不支持此類型郵件  #####");
    }
    for (String email : receiveMails) {
      try {
        sendEmail(email, context, subject, emailParam);
        log.info("發送郵件 至:  " + email + "  成功");
        successSum++;
      } catch (Exception e) {
        log.info("發送郵件 至:  " + email + "  失敗,異常信息:" + e.getMessage(), e);
        errSum++;
        errEmails.append(email + ",");
      }
    }
    resultMap.put("successSum", successSum);
    resultMap.put("errSum", errSum);
    if (errSum > 0) {
      resultMap.put("errEmails", errEmails.deleteCharAt(errEmails.length() - 1).toString());
    }
    return resultMap;
  }

  private static void sendEmail(
      String mailto, String context, String subject, Map<String, Object> emailParam)
      throws EmailException {
    String host = (String) emailParam.get("host");
    String charset = (String) emailParam.get("charset");
    String username = (String) emailParam.get("username");
    String password = (String) emailParam.get("password");

    HtmlEmail email = new HtmlEmail();
    email.setHostName(host);
    email.setCharset(charset);
    email.setAuthentication(username, password);
    email.setFrom(username, "");
    email.setSubject(subject);
    email.setHtmlMsg(context);
    email.addTo(mailto);
    String send = email.send();
    log.info("send = " + send);
  }

  // 獲取html模板
  private static String getContext(Map<String, Object> datamap, String templateName) {
    Context context = new Context();
    context.setVariables(datamap);
    return templateEngine.process(templateName, context);
  }
}

五,使用

  private Map<String, Object> sendEmail(TaskInfoDTO taskInfo) throws Exception {
    Map<String, Object> datamap = new HashMap<>();
    String context = null;
    // ...
    // context 發送內容
    // ...
    datamap.put("context", context);
    Map<String, Object> emailParam = new HashMap<>();
    emailParam.put("host", host);
    emailParam.put("charset", charset);
    emailParam.put("username", username);
    emailParam.put("password", password);
    emailParam.put("templateName", templateName);
    emailParam.put("subject", subject);
    emailParam.put("receiveMails", receiveMails);
    return EmailTool.sendEmail(datamap, emailParam, "1");
  }

六,效果圖

郵件模板寫的很簡單,如需其他樣式自行修改模板。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章