【java】javamail+freemarker生成邮件模板,并发送邮件

一、前言

      在上一篇博客中小编向大家介绍了发送带附件的邮件,实践一下也是不错的。这一篇博客是为下一篇博客进行铺垫的,因为项目中需要一个推送的功能,要把推送的信息灵活的显示到一个固有的模板上。所以为了达到这个目的,小编就引入了freemarker。下面向大家介绍。

二、What is Apache FreeMarker?

      FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页、电子邮件、配置文件、源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。【百度百科】


这里写图片描述

      既然他是一个模板引擎,所以可以通过固定的模板,然后把数据补充进去,就可以达到使用的目的了。 我们有了模板+数据,再由freemarker组合就可以生成我们要的界面。

      这种方法通常被称为MVC(模型视图控制器)模式,并且特别适用于动态网页。它有助于将网页设计师(HTML作者)与开发人员(Java程序员通常)分开。设计师不会在模板中面对复杂的逻辑,并且可以改变页面的外观,而不需要修改或重新编译代码。

三、生成邮件模板并发送

      可以先看一下我的设计模板样式,其中的所有的数据都需要是可变化的:


这里写图片描述

      推荐几篇博客:

freemarker语法总结

四、小结

4.1 环境说明

  • freemarker.jar

  • mail.jar

  • FreeMarkerIDE,包含两个文件features和plugins,放到eclipse中。

4.2 具体

      freemarker工具类:

      这里要提示的是cfg.setClassForTemplateLoading(this.getClass(), “/com/dmsd/mail/ftl”);指明了模板存放的位置。

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 {

    /**
     * 获取模板信息
     * @param name 模板名
     * @return
     */
    public Template getTemplate(String name){
        //通过freemarkerd COnfiguration读取相应的ftl
        Configuration cfg = new Configuration();
        //设定去哪里读取相应的ftl模板文件,指定模板路径
        cfg.setClassForTemplateLoading(this.getClass(), "/com/dmsd/mail/ftl");
        try {
            //在模板文件目录中找到名称为name的文件
            Template template =  cfg.getTemplate(name);
            return template;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    } 
    /**
     * 输出到控制台
     * @param name
     * @param root
     * @throws TemplateException
     * @throws IOException
     */
    public void print(String name,Map<String,Object> root) throws TemplateException, IOException {
        //通过Template可以将模板文件输出到相应的流
        Template template = this.getTemplate(name);
        template.process(root, new PrintWriter(System.out));
    }

    /**
     * 输出到文件中
     * @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));
            //获取模板
            Template template = this.getTemplate(name);
            //设置模板编码
            template.setEncoding("utf-8");
            try {
                //输出
                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类:提供数据

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模板
     * @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(
                        "解聘通知书",
                        time,
                        "欢迎使用ITOO云平台",
                        "站在巨人的肩膀上",
                        "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",
                        "不怕不知道,就怕不知道",
                        "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"   );

    }
}

      模板:index.html
      在这个模板中,使用<#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>
张先生:<br/>
         您于2013年9月1日在我公司单担任 总经理 职务,<br/>
         根据公司有关规定及您的工作绩效和表现,您不适合本公司此职位,<br/>
         故决定自2017年5月23日起,本公司解除与您的聘雇劳动关系,<br/>
         请在收到通知书二日内在公司办公室办理相关离职手续。<br/>
         非常感谢您在本公司的辛勤工作!同时祝愿您在未来有更好的发展!<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 0; padding:0 10px; font-size:18px; color:#363c4c;">变是永远<span style="font-size:40px; color:#f44336; font-style:italic;">不变</span></div>
    <div style="margin:10px 0 0; padding:0 10px; font-size:18px; color:#363c4c;">没有教不好的学生,只有不会教的老师!</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;">扫一扫关注公众号</div>
                    </div>
                    </div>

      footer.ftl:

<br/>
<div style="background:#3587f2; padding:12px; line-height:1.8; font-size:14px; color:#fff;">提示:请不要对此邮件直接回复,系统看不懂您的回信^_^。如果您有建议或意见,请回复
    <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>

      生成效果:


这里写图片描述

      发送邮件后,可以借鉴《【java】javamail简介以及发送邮件》

四、小结

      通过对freemarker的使用,其中的一些标签等使用也是比较重要的,还有就是存储数据的时候,要把数据放入到map中,然后在前台取。

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 12
    评论
要使用Freemarker模板发送邮件,需要进行以下步骤: 1. 导入需要的依赖 在Maven项目中,需要在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-tools</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency> ``` 2. 编写Freemarker模板 比如我们可以编写一个简单的模板,如下: ``` <html> <body> <h1>Hello ${username}!</h1> <p>Here is your message:</p> <p>${message}</p> </body> </html> ``` 在模板中,我们可以使用Freemarker的语法来动态生成HTML内容。 3. 编写Java代码 我们可以编写一个名为`EmailService`的Java类来发送邮件。 首先,我们需要创建一个`VelocityEngine`对象,来加载Freemarker模板: ``` VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.init(); ``` 然后,我们可以使用`VelocityEngine`对象来加载模板文件: ``` Template template = velocityEngine.getTemplate("email-template.vm"); ``` 接下来,我们需要创建一个`VelocityContext`对象,并将模板中需要填充的变量添加到该对象中: ``` VelocityContext context = new VelocityContext(); context.put("username", username); context.put("message", message); ``` 最后,我们可以使用`JavaMail`库来发送邮件: ``` Properties properties = new Properties(); properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); Session session = Session.getInstance(properties, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(fromEmail, password); } }); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromEmail)); message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail)); message.setSubject(subject); StringWriter writer = new StringWriter(); template.merge(context, writer); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(writer.toString(), "text/html"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); Transport.send(message); ``` 在以上代码中,我们首先创建了一个`Properties`对象来配置邮件服务器的信息。然后,我们创建了一个`Session`对象,并使用`Authenticator`对象来进行SMTP认证。接着,我们创建了一个`MimeMessage`对象,并设置了邮件的发送者、接收者和主题。然后,我们将模板生成的HTML内容添加到`MimeBodyPart`对象中,最后将`MimeBodyPart`对象添加到`Multipart`对象中,并将`Multipart`对象设置为邮件的内容。最后,我们使用`Transport`对象的`send`方法来发送邮件。 这就是使用Freemarker模板发送邮件的基本步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你个佬六

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值