java發送html模板郵件

線上頁面代碼模板
BW5O6x.png
BWoEG9.png

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>公衆號兌換卡密</title>
    <style>
        body, div, p, ul, li, a {
            margin: 0;
            padding: 0;
            list-style: none;
            text-decoration: none;
        }

        .wrap {
            width: 750px;
            height: 100%;
            margin: 0 auto;
        }

        nav {
            font-weight: 700;
            padding: 20px 10px;
            box-sizing: border-box;
            background: #f9f9f9;
        }

        .nav-title {
            margin: 0 0 20px;
        }

        .nav-content, .nav-end, .card-time {
            font-size: 15px;
            line-height: 30px;
        }

        .nav-tel {
            color: #ff143f;
        }

        .list {
            width: 750px;
            margin: 20px 0;
        }

        .list ul {
            width: 100%;
            height: 36px;
            font-size: 13px;
            display: flex;
            align-items: center;
            /* justify-content: space-around; */
            background: #e4e4e4;
            border-radius: 8px 8px 0 0;
        }

        .list .list-ul {
            background: #fff;
            border-radius: 0;
            height: 52px;
            line-height: 52px;
            background: #f9f9f9;
        }

        .list .list-ul li {
            font-size: 12px;
        }

        /*產品名稱*/
        .goodsName {
            text-align: center;
            width: 150px;
            padding-left: 6px;
        }
        .goodsName-li{
            width: 150px;
            text-align: center;
        }
        .orderNo  {
            text-align: center;
            width: 175px;
        }
        .orderNo-li  {
            text-align: center;
            width: 175px;
        }
        .facePrice  {
            text-align: right;
            width: 75px;
        }
        .facePrice-li{
            width: 75px;
            text-align: center;
        }
        .cardNo  {
            text-align: center;
            width: 150px;
        }
        .cardNo-li  {
            text-align: center;
            width:150px;
        }

        .cardPwd  {
            text-align: center;
            width: 75px;
        }
        .cardPwd-li  {
            text-align: center;
            width: 75px;
        }
        .cardDate{
            text-align:center; width: 125px;
        }
    </style>
</head>
<body>
<div class="wrap">
    <!-- 上部分導航 -->
    <nav>
        <p class="nav-title">尊敬的用戶您好:</p>
        <p class="nav-content">以下是您在【資和信籤紙賀】公衆號兌換的電子卡劵的卡號、卡密及有效期,點擊電子卡名稱可查看該電子卡
            的使用說明,請在有效期限內使用您的各項卡劵。
        </p>
        <p class="nav-end">如禮品卡兌換過程中有任何疑問,請撥打客服電話 <span class="nav-tel">95159</span> 。感謝您的使用!</p>
        <p class="card-time">髮卡日期:<span id="time"></span></p>
    </nav>
    <!-- 下部分列表數據 -->
    <div class="list" id="table-head">
        <ul>
            <li class="goodsName-li">名稱</li>
            <li class="orderNo-li">訂單號</li>
            <li class="facePrice-li">金額</li>
            <li class="cardNo-li">卡號</li>
            <li class="cardPwd-li">密碼</li>
            <li class="cardDate">卡劵有效期</li>
        </ul>
    </div>
</div>
</body>
</html>

--後期所以css樣式基於模板進行修改就非常簡單,不用修改java程序代碼

import cn.hutool.extra.mail.MailUtil;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: SimonHu
 * @Date: 2020/11/5 8:59
 * @Description:
 */
@Service
public class SendHTMLMail {
    private static final Logger log = LoggerFactory.getLogger(SendHTMLMail.class);
    @Autowired
    private ResourceLoader resourceLoader;
    
    public static void main(String[] args) {
        List<Map> list = new ArrayList<Map>();
        Map map = new HashMap();
        map.put("cardNo", "11111");
        map.put("cardPwd", "11111");
        Map map2 = new HashMap();
        map2.put("cardNo", "http://www.baidu.com");
        map2.put("cardPwd", "11111");
        list.add(map);
        list.add(map2);
        SendHTMLMail sendHTMLMail = new SendHTMLMail();
        sendHTMLMail.sendSimpleMail("[email protected]", "10001", list);
    }
    
    /**
     * @param sendMail
     * @param orderNo
     * @param sendJson
     * @return void
     * @Description:發送郵件
     * @Author:SimonHu
     * @Date: 2020/11/5 10:25
     */
    public void sendSimpleMail(String sendMail, String orderNo, List<Map> sendJson) {
        SAXReader reader = new SAXReader();
        Document document = null;
        FileWriter fwriter = null;
        XMLWriter writer = null;
        FileReader in = null;
        try {
            //獲取模板html文檔
            Resource resource = resourceLoader.getResource("classpath:mail/mailTemple.html");
            document = reader.read(resource.getInputStream());
            Element root = document.getRootElement();
            //獲取id爲time的節點。
            Element time = getNodes(root, "id", "time");
            Element tableHead = getNodes(root, "id", "table-head");
            //設置髮卡日期
            time.setText(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            Element tabElement = this.tableDocument(orderNo, sendJson);
            if (tabElement != null) {
                tableHead.appendContent(tabElement);
            }
            //保存到臨時文件
            fwriter = new FileWriter("classpath:temp.html");
            writer = new XMLWriter(fwriter);
            writer.write(document);
            writer.flush();
            //讀取臨時文件,並把html數據寫入到字符串str中,通過郵箱工具發送
            in = new FileReader("classpath:temp.html");
            char[] buff = new char[1024 * 10];
            in.read(buff);
            String str = new String(buff);
            log.info("================開始發送郵件======================");
            MailUtil.send(sendMail, "【籤紙賀】公衆號兌換卡密", str.toString(), true);
            log.info("================郵件發送完成======================");
        } catch (Exception e) {
            log.error("------sendSimpleMail-----", e);
        } finally {
			//關閉流
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != writer) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != fwriter) {
                try {
                    fwriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    /**
     * @param orderNo
     * @param sendJson
     * @return java.lang.String
     * @Description:獲取table數據
     * @Author:SimonHu
     * @Date: 2020/11/5 9:32
     */
    public Element tableDocument(String orderNo, List<Map> sendJson) {
        StringBuffer eamilContext = new StringBuffer();
        if (sendJson != null && !sendJson.isEmpty()) {
            for (Map map : sendJson) {
                eamilContext.append("<ul class=\"list-ul\"><li class=\"goodsName\" ><a href=\"https://xxx/xxx/order/xxx?xxx=")
                        .append(map.get("goodsId")).append("\" style=\"color:#007eff;\">")
                        .append(map.get("goodsName"))
                        .append("</a></li><li class=\"orderNo\" >").append(orderNo)
                        .append("</li><li class=\"facePrice\">")
                        .append(map.get("facePrice"));
                if (String.valueOf(map.get("cardNo")).indexOf("http") == -1) {
                    eamilContext.append("</li><li class=\"cardNo\" >").append(map.get("cardNo"));
                } else {
                    eamilContext.append("</li><li class=\"cardNo\"><a href=\"").append(map.get("cardNo")).append("\" style=\"color:#007eff;\">去使用</a>");
                }
                eamilContext.append("</li><li class=\"cardPwd\">")
                        .append(map.get("cardPwd"))
                        .append("</li><li class=\"cardDate\">").append(map.get("expireTime")).append("</li></ul>");
            }
        }
        String htmlStr = "<div>" + eamilContext.toString() + "</div>";
        try {
            Document document = DocumentHelper.parseText(htmlStr);
            return document.getRootElement();
        } catch (DocumentException e) {
            log.error(e.getMessage());
        }
        return null;
    }
    
    /**
     * 方法描述:遞歸遍歷子節點,根據屬性名和屬性值,找到對應屬性名和屬性值的那個子孫節點。
     *
     * @param node      要進行子節點遍歷的節點
     * @param attrName  屬性名
     * @param attrValue 屬性值
     * @return 返回對應的節點或null
     */
    public Element getNodes(Element node, String attrName, String attrValue) {
        // 當前節點的所有屬性
        final List<Attribute> listAttr = node.attributes();
        // 遍歷當前節點的所有屬性
        for (final Attribute attr : listAttr) {
            // 屬性名稱
            final String name = attr.getName();
            // 屬性的值
            final String value = attr.getValue();
//            System.out.println("屬性名稱:" + name + "---->屬性值:" + value);
            if (attrName.equals(name) && attrValue.equals(value)) {
                return node;
            }
        }
        // 遞歸遍歷當前節點所有的子節點
        // 所有一級子節點的list
        final List<Element> listElement = node.elements();
        //遍歷所有一級子節點
        for (Element e : listElement) {
            Element temp = getNodes(e, attrName, attrValue);
            // 遞歸
            if (temp != null) {
                return temp;
            }
            ;
        }
        return null;
    }
}

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