使用freemarker做邮件发送模板

1、解析工具类

package com.example.springbootfreemarker.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

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

public class FreeMarkerTemplateUtil {

    public String getEmailHtml(Map map, String templateName) {

        String htmlText = "";
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_27);
        try {
            //加载模板路径
            configuration.setClassLoaderForTemplateLoading(ClassLoader.getSystemClassLoader(),"ftl");
            //获取对应名称的模板
            Template template = configuration.getTemplate(templateName);
            //渲染模板为html
            htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return htmlText;
    }

    /**
     * 输出到控制台
     */
    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 模板名
     * @return
     */
    public Template getTemplate(String name) {
        //通过freemarkerd Configuration读取相应的ftl
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
        //设定去哪里读取相应的ftl模板文件,指定模板路径
        cfg.setClassLoaderForTemplateLoading(ClassLoader.getSystemClassLoader(), "ftl");
        try {
            //在模板文件目录中找到名称为name的文件
            Template template = cfg.getTemplate(name);
            return template;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

测试:

   //填充模板文件中的参数值
    Map<String, Object> root = null;
    FreeMarkerTemplateUtil freeMarkerTemplateUtil = null;

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

    @Test
    public void testCreateHtml() throws Exception{

        root.put("username", "admin");

        String emailHtml = freeMarkerTemplateUtil.getEmailHtml(root, "reg.ftl");
//        System.out.println(">>>>" + emailHtml);

        root.put("username", "root");
        freeMarkerTemplateUtil.print("reg.ftl", root);

    }

 

源码参照:使用freemarker做邮件发送模板

转载于:https://www.cnblogs.com/kingsonfu/p/10389790.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用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模板发送邮件的基本步骤。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值