[java] javamail+freemarker generates mail template and sends mail

Posted by ilight on Thu, 27 Jun 2019 00:20:59 +0200

I. Preface

In the last blog, a small editor introduced you. Send mail with attachments It's also good to practice. This blog paves the way for the next blog, because a push function is needed in the project to display the push information flexibly to an inherent template. So in order to achieve this goal, freemarker is introduced into the edition. Here's an introduction.

What is Apache FreeMarker?

FreeMarker is a template engine: a generic tool based on templates and data to be changed to generate output text (HTML pages, e-mail, configuration files, source code, etc.). It's not for end users, it's a Java class library, a component that programmers can embed into the products they develop. Baidu Encyclopedia


Since he is a template engine, it can be used by fixing the template and then adding the data. We have template + data, and then freemarker combines to generate the interface we want.

This method is often called MVC (Model View Controller) mode and is especially suitable for dynamic web pages. It helps to separate web designers (HTML authors) from developers (Java programmers usually). Designers do not face complex logic in templates, and can change the appearance of the page without modifying or recompiling the code.

3. Generate mail template and send it

Let's first look at my design template style, where all the data needs to be changeable:


Recommend several blogs:

A comprehensive freemarker tutorial

Java: Configuration and Use of FreeMarker

freemarker Syntax Summary

Summary

4.1 Environmental Description

  • freemarker.jar

  • mail.jar

  • FreeMarkerIDE, which contains two files features and plugins, is put into eclipse.

4.2 Specific

freemarker Tool Class:

The prompt here is cfg.setClassForTemplate Loading (this.getClass(), "/com/dmsd/mail/ftl"); indicating where the template is stored.

package com.dmsd.freemarker.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;


public class FreemarkerUtil {

    /**
     * Getting template information
     * @param name Template name
     * @return
     */
    public Template getTemplate(String name){
        //Read the corresponding ftl through freemarkerd COnfiguration
        Configuration cfg = new Configuration();
        //Set where to read the corresponding ftl template file, specify the template path
        cfg.setClassForTemplateLoading(this.getClass(), "/com/dmsd/mail/ftl");
        try {
            //Find a file named name in the template file directory
            Template template =  cfg.getTemplate(name);
            return template;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    } 
    /**
     * Output to console
     * @param name
     * @param root
     * @throws TemplateException
     * @throws IOException
     */
    public void print(String name,Map<String,Object> root) throws TemplateException, IOException {
        //Template enables template files to be exported to the corresponding stream
        Template template = this.getTemplate(name);
        template.process(root, new PrintWriter(System.out));
    }

    /**
     * Output to file
     * @param name
     * @param root
     * @throws TemplateException
     * @throws IOException
     */
    public void fprint(String name,Map<String,Object> root,String outFile)  {
        FileWriter out=null;
        try {
            out = new FileWriter(new File("E:/"+outFile));
            //Getting Templates
            Template template = this.getTemplate(name);
            //Setting Template Coding
            template.setEncoding("utf-8");
            try {
                //output
                template.process(root, out);
            } catch (TemplateException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();

        }finally{
            try {
                if (out!=null) {
                    out.close();
                }
            } catch (Exception e2) {
            }
        }
    }
}

Object class: Provide data

package com.dmsd.test;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


import org.junit.Before;
import org.junit.Test;


import com.dmsd.freemarker.util.FreemarkerUtil;
import com.dmsd.mail.model.Itoo;

import freemarker.template.TemplateException;


public class testfreemarker {
    FreemarkerUtil fuFreemarkerUtil;
    Map<String, Object> root = null;

    @Before
    public void setUp(){
        fuFreemarkerUtil=new FreemarkerUtil();
        root = new HashMap<String, Object>();
    }

    private void sprint(String name) throws TemplateException, IOException{
        fuFreemarkerUtil.print(name, root);
    }

    private void fprint(String name,String filename) {
        fuFreemarkerUtil.fprint(name, root, filename);
    }

    /**
     * ITOO Template
     * @throws Exception
     */
    @Test
    public void testCreateHtml() throws Exception{

        Date date=new Date();
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        String time=format.format(date);

        Itoo itooList=  new Itoo(
                        "Notice of dismissal",
                        time,
                        "Welcome to use ITOO Cloud Platform",
                        "Standing on the shoulders of giants",
                        "http://www.tfjybj.com",
                        "http://192.168.22.208/group1/M00/00/00/wKgW0Fkjp0SANTXDAAGh7DpPo2E431_big.png",
                        "http://baike.baidu.com/link?url=fl7uIbBoz9rWvJ8g2kSdcM7a-NRttA2gDQxu6pH9CLwkKgJ3Wl_Z1zn2OoqgxJhXenjdOyn3Bde5mH_hoJwytuC7Joj2hQCcyspGqAe1Bvx59pUq5RSoukPqdxI96NIH",
                        "Don't be afraid of not knowing, just afraid of not knowing.",
                        "http://192.168.22.208/group1/M00/00/00/wKgW0FkjqMqAGm-3AABvODFU6hI303_big.jpg",
                        "18333602097@163.com"
                        );

        root.put("itooList", itooList);

        this.sprint("index.ftl");
        this.fprint("index.ftl", "Ares.html"   );

    }
}

Template: index.html
In this template, other templates are introduced using <#include "head.ftl">.

      index.ftl:

<html>
  <head>
    <title>index.html</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  </head>
 <body>
 <div style="padding:40px 0; height:auto; min-height:100px; text-align:center;">
            <div align="center" style="margin:0 auto; min-width:290px; max-width:750px;">
                <div style="margin:0; background:#fff; border-radius:8px;">
                    <#include "head.ftl">
                    <#include "QEcode.ftl">
                </div>  
                    <#include "footer.ftl"> 
                </div>
            </div>
        </div>
    </body>
</html>

      head.ftl:

<div style="background:#f2f2f2;">
    <div style="background:url(http://192.168.22.208/group1/M00/00/00/wKgW0FkjpfqAJAPnAAAlhmNDKpE469_big.png) center top #f2f2f2 no-repeat; height:191px; text-align:left; position:relative; border-radius:8px 8px 0 0;">
        <div style="padding:26px 0 0; color:#fff; font-size:42px; font-weight:100; text-align:center;">${itooList.title}</div>

        <div style="margin:5px 0 0; color:#fff; font-size:20px; font-weight:100; text-align:center;">${itooList.date}</div>

        <div style="margin:15px 0 30px; padding:0 10px; color:#fff; font-size:16px; font-weight:100; line-height:1.4; text-align:center;">${itooList.welcome}</div>
    </div>
</div>

<div style="margin:10px 0 0; padding:0 10px; font-size:18px; color:#363c4c;">
<pre>
<p>
Mr. Zhang: <br/>
         On September 1, 2013, you held the position of general manager in our company, <br/>.
         According to the company's relevant regulations and your performance, you are not suitable for this position in our company, <br/>.
         Therefore, it is decided that from May 23, 2017, our company will terminate the employment relationship with you, <br/>.
         Please go through the relevant departure formalities within 2 days after receipt of the notice. <br/>
         Thank you very much for your hard work in our company! At the same time, I wish you better development in the future. <br/>
</p>
</pre>
</div>

<div style="background:#fff; position:relative; margin:10px 20px 0; padding:0 0 60px; border-bottom:1px solid #f1f1f1; border-radius:3px;">

    <div style="padding:40px 0 0; font-size:34px;">${itooList.notice}</div>
    <div style="margin:10px 0;padding:0 10px;font-size:18px;color:c4c;">change is always <span style="font-size:40px;color:;font-style:italic;">unchanged </span>of </div>
    <div style="margin:10px 0;padding:0 10px;font-size:18px;color:#363;c4c;">There are no bad students, only teachers who can't teach! </div>
</div>

      QEcode.ftl:

<div>
    <div>
                        <a href="${itooList.logolink}" style="margin:30px 0 0; width:300px; display:inline-block; text-decoration:none; color:##363c4c;" target="_blank"><img src="${itooList.logo}" style="
                        width: 150px;
                    "></a>
                    </div>

                    <div style="margin:5px 0 0; font-size:16px; color:#363c4c;">
                        <a href="${itooList.teacherlink}" style="margin:30px 0 0; width:300px; display:inline-block; text-decoration:none; color:##363c4c;" target="_blank">${itooList.teacherword}</a>
                    </div>

                    <div style="margin:30px 0 0; width:300px; display:inline-block;">
                        <div><img src="${itooList.QRcode}"style="width: 150px;"></div>

                        <div style="margin:5px 0 0; font-size:16px; color:#363c4c;">Sweep the Public Number</div>
                    </div>
                    </div>

      footer.ftl:

<br/>
<div style="background:#3587f2; padding:12px; line-height:1.8; font-size:14px; color:#fff;">Tip: Please don't reply to this email directly. The system can't understand your reply.^_^. If you have any suggestions or comments, please reply.
    <a href="mailto:${itooList.email}" style="text-decoration:none; color:#fff;">${itooList.email}</a>
</div>


<div style="background:url(http://192.168.22.208/group1/M00/00/00/wKgW0FkjpiuAO_ZOAAAC3nG29KQ692_big.png) bottom repeat-x; height:90px; border-radius:0 0 8px 8px; position:relative;">
</div>

Generating effects:


After sending an email, you can learn from it. "Introduction to [java] javamail and sending mail"

Summary

Through the use of freemarker, some of the tags are also more important, and when storing data, the data should be put into the map and fetched in the front desk.

Topics: FreeMarker Java Junit Apache