Spring中使用FreeMaker或Vilocity模板发送邮件 (转)

11 篇文章 0 订阅
6 篇文章 0 订阅
 本文以用户注册后为用户发送一封邮件为例子,讲述如何在Spring中使用FreeMaker或Vilocity发送邮件。

       Spring配置文件:
<!-- 使用Spring封装的Mail Sender -->
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.163.com"/>
        <property name="username" value="test"/>
        <property name="password" value="123456"/>
        <property name="javaMailProperties">
              <props>
                <prop key="mail.smtp.auth">true</prop>
              </props>
        </property>
    </bean>

    <!-- freemarker config -->
    <bean id="freeMarkerConfigurer"                    class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="/WEB-INF/freemakertemplate/" />
        <property name="freemarkerSettings">
            <props>
                <prop key="template_update_delay">0</prop>
                <prop key="default_encoding">GBK</prop>
                <prop key="locale">zh_CN</prop>
            </props>
        </property>
    </bean>
   
    <!-- vilocity config -->
    <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
        <property name="resourceLoaderPath" value="/WEB-INF/vilocitytemplate/" />
        <property name="velocityProperties">
            <props>
                <prop key="velocimacro.library">*.vm</prop>
                <prop key="default.contentType">text/html; charset=utf-8</prop>
                <prop key="output.encoding">utf-8</prop>
                <prop key="input.encoding">utf-8</prop>
            </props>
        </property>
    </bean>
   
     <bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage" singleton="false">
        <property name="from" value=">
    </bean>
   
    <bean id="mailEngine" class="test.MailEngine">
        <property name="mailSender" ref="mailSender"/>
        <!-- 如果使用Vilocity -->
        <property name="velocityEngine" ref="velocityEngine"/>
       <!-- 如果使用FreeMaker -->
       <property name="freeMarkerConfigurer" ref="freeMarkerConfigurer" />
    </bean>
   
 
    MailEngine类:

public class MailEngine {
    protected static final Log log = LogFactory.getLog(MailEngine.class);

//    private FreeMarkerConfigurer freeMarkerConfigurer;
    private VelocityEngine velocityEngine;
    private MailSender mailSender;

//    public void setFreeMarkerConfigurer(
//            FreeMarkerConfigurer freeMarkerConfigurer) {
//        this.freeMarkerConfigurer = freeMarkerConfigurer;
//    }

    public void setMailSender(MailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void setVelocityEngine(VelocityEngine velocityEngine) {
        this.velocityEngine = velocityEngine;
    }

    /**
     * 通过模板产生邮件正文
     * @param templateName    邮件模板名称
     * @param map            模板中要填充的对象
     * @return 邮件正文(HTML)
     */
    public String generateEmailContent(String templateName, Map map) {
        //使用FreeMaker模板
//        try {
//            Configuration configuration = freeMarkerConfigurer.getConfiguration();
//            Template t = configuration.getTemplate(templateName);
//            return FreeMarkerTemplateUtils.processTemplateIntoString(t, map);
//        } catch (TemplateException e) {
//            log.error("Error while processing FreeMarker template ", e);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//            //log.error("Error while open template file ", e);
//        } catch (IOException e) {
//            log.error("Error while generate Email Content ", e);
//        }
       
//        使用Vilocity模板
        try {
           return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateName, map);
        } catch (VelocityException e) {
            log.error("Error while processing Vilocity template ", e);
        }
       
        return null;
    }

    /**
     * 发送邮件
     * @param emailAddress        收件人Email地址的数组
     * @param fromEmail            寄件人Email地址, null为默认寄件人

web@vnvtrip.com
     * @param bodyText            邮件正文
     * @param subject            邮件主题
     * @param attachmentName    附件名
     * @param resource            附件
     * @throws MessagingException
     */
    public void sendMessage(String[] emailAddresses, String fromEmail,
            String bodyText, String subject, String attachmentName,
            ClassPathResource resource) throws MessagingException {
        MimeMessage message = ((JavaMailSenderImpl) mailSender)
                .createMimeMessage();

        // use the true flag to indicate you need a multipart message
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setTo(emailAddresses);
        if(fromEmail != null){
            helper.setFrom(fromEmail);
        }
        helper.setText(bodyText, true);
        helper.setSubject(subject);
       
        if(attachmentName!=null && resource!=null)
            helper.addAttachment(attachmentName, resource);

        ((JavaMailSenderImpl) mailSender).send(message);
    }

    /**
     * 发送简单邮件
     * @param msg   
     */
    public void send(SimpleMailMessage msg) {
        try {
            ((JavaMailSenderImpl) mailSender).send(msg);
        } catch (MailException ex) {
            //log it and go on
            log.error(ex.getMessage());
        }
    }
   
    /**
     * 使用模版发送HTML格式的邮件
     *
     * @param msg          装有to,from,subject信息的SimpleMailMessage
     * @param templateName 模版名,模版根路径已在配置文件定义于freemakarengine中
     * @param model        渲染模版所需的数据
     */
    public void send(SimpleMailMessage msg, String templateName, Map model) {
        //生成html邮件内容
        String content = generateEmailContent(templateName, model);
        MimeMessage mimeMsg = null;
        try {
            mimeMsg = ((JavaMailSenderImpl) mailSender).createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true, "utf-8");
            helper.setTo(msg.getTo());
           
            if(msg.getSubject()!=null)
                helper.setSubject(msg.getSubject());
           
            if(msg.getFrom()!=null)
                helper.setFrom(msg.getFrom());
           
            helper.setText(content, true);
           
            ((JavaMailSenderImpl) mailSender).send(mimeMsg);
        } catch (MessagingException ex) {
            log.error(ex.getMessage(), ex);
        }

    }
}

发送邮件:
SimpleMailMessage message = (SimpleMailMessage) getBean("mailMessage");
                message.setTo(user.getName() + "<" + user.getEmail() + ">");
               
                Map<String, User> model = new HashMap<String, User>();
                model.put("user", user);
               
                MailEngine engine = (MailEngine)getBean("mailEngine");
                //Vilocity模板
                engine.send(message, "notifyUser.vm", model);
                //FreeMaker模板
                //engine.send(message, "NotifyUser.ftl", model);

以上的User为用户类。

Vilocity模板:
${user.name} 您好!您已成功注册为本站会员,您的信息如下:

${user.name}
${user.password}

FreeMaker模板:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>用户注册通知</title>
</head>
<body>
<p>${user.name} 您好,恭喜您,已经成为本站会员!</p>
<table>
<tr><td>用户名:</td><td>${user.name}</td></tr>
<tr><td>密码:</td><td>${user.password}</td></tr>
</table>
</body>
</html

使用freemarker发送邮件,您可以按照以下步骤进行操作: 1. 首先,确保您的项目已经引入了freemarker的依赖。 2. 创建一个freemarker模板文件,用于邮件的内容。您可以在模板文件使用freemarker的语法来生成动态内容。 3. 在您的邮件发送代码,引入freemarker的相关类库和配置。根据您提供的引用,可以看到邮件发送代码引入了MailService类。 4. 在邮件发送代码使用freemarker的Template类加载模板文件。 5. 准备要发送的邮件内容,可以将模板需要动态替换的部分传递给Template对象,使用Template.process()方法生成最终的邮件内容。 6. 使用MailService类的sendMessageMail()方法发送邮件,将生成的最终邮件内容作为参数传递给该方法。 需要注意的是,您还需要在应用程序的配置文件(如application.properties或application.yml)配置邮件服务器的相关信息,如SMTP服务器的主机名、端口号和编码方式。根据您提供的引用,可以看到spring boot的配置设置了邮件服务器的相关信息,如host和port。 通过以上步骤,您可以使用freemarker发送邮件并实现内容的动态生成和发送。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [spring clould利用freemaker发送邮件,已实锤,可发送内置图片和附件,抄送,暗送](https://blog.csdn.net/xuedengyong/article/details/88895881)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [利用freemaker实现发送读取模板并带有附件的邮件](https://blog.csdn.net/weixin_44162830/article/details/104048167)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值