zoukankan      html  css  js  c++  java
  • Spring邮件发送2

    前言:上一篇博文讲解了邮件发送的基础用法(数据是写死的),然而在实际开发中,大多数情况下邮件内容都是根据业务来动态生成的。所以在此篇博文中,我们将讲解邮件发送携带数据的几种方案。

    一、解析自定义占位符

      实现方法: 通过解析自定义占位符,将传递到邮件中的数据,转换成html内容,进行发送。

    1)占位符替换函数

    /**
     * Replaces place holder ("${}") string in template with values in Map
     * 
     * @param template
     * @param models
     * @return
     */
    public static String replacePlaceHolder(String template, Map<String, String> models) {
    
        if (template.indexOf("${") == -1) {
            return template;
        }
        
        while (true) {
        
            int start = template.indexOf("${");
            int end = template.indexOf("}", start);
            
            if (start != -1 && end != -1) {
                
                String key = template.substring(start + 2, end);
                
                if (models.containsKey(key)) {
                    template = template.substring(0, start) + models.get(key) + template.substring(end + 1);
                }
                
            } else {
                break;
            }
            
        }
        
        return template;
        
    }

    2) 邮件发送Test-Case

    // 1. Resolve html template to real text
    String htmlTemplate = "<html lang='zh-cn'><head></head><body><h1>发送带模板数据的Email</h1><p>你好,${username}。本次您的验证码为${code},请妥善保管</p></body></html>";
            
    Map<String, String> models = new HashMap<String, String>();
    models.put("username", "XXX");
    models.put("code", "4551");
            
    String text = StringUtils.replacePlaceHolder(htmlTemplate, models);
            
    // 2. send email
    boolean result = mailHandler.sendText("收件人邮箱", "发送带模板数据的Email", text);
    Assert.assertEquals(true, result);

    二、使用Velocity模板

      实现方法:借用VelocityEngineUtils合并Velocity模板和数据,得到要发送的Email, 进行发送。

    1) 引入依赖jar包

    <!-- velocity -->
    <dependency>
        <groupId>org.apache.velocity</groupId>
        <artifactId>velocity</artifactId>
        <version>1.7</version>
    </dependency>

    2) 配置Velocity模板引擎

    <!-- Define velocity engine -->
    <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
        <property name="configLocation" value="classpath:velocity.properties" />
    </bean>
    velocity.properties:
    input.encoding=UTF-8
    output.encoding=UTF-8
    resource.loader=class
    class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader

    3) 发送邮件实现函数

    // Get email content by velocity merge models
    String content = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, encoding, models);

    // Send email MimeMessage mimeMessage
    = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, encoding); helper.setFrom(form); // set sender helper.setTo(to); // set recipients helper.setSubject(subject); helper.setText(content, true); // Indicate the text included is HTML mailSender.send(mimeMessage);

    三、使用FreeMarker模板

      实现方法:借用FreeMarkerTemplateUtils合并FreeMarker模板和数据,得到要发送的Email, 进行发送。

    1) 引入依赖jar包

    <dependency>
      <groupId>org.freemarker</groupId>
      <artifactId>freemarker</artifactId>
      <version>2.3.23</version>
    </dependency>

    2)配置FreeMarker

    <!-- Define freemarker configuration -->
    <bean id="freeMarkerConfiguration" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
      <property name="templateLoaderPath" value="classpath:template/freemarker" />
      <property name="defaultEncoding" value="utf-8" />
      <property name="freemarkerSettings">
         <props>
             <prop key="template_update_delay">10</prop>
             <prop key="locale">zh_CN</prop>
          <prop key="number_format">#.##</prop>
        </props>
      </property>
    </bean>

    3) 发送邮件实现函数

    // Get email content by freeMarker template
    Template realTemplate = freeMarkerConfigurer.getTemplate(template); String content = FreeMarkerTemplateUtils.processTemplateIntoString(realTemplate, models);

    // Send email
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, encoding);
    helper.setFrom(form);           // set sender
    helper.setTo(to);               // set recipients
    helper.setSubject(subject);
    helper.setText(content, true);  // Indicate the text included is HTML
    mailSender.send(mimeMessage);
  • 相关阅读:
    54.Spiral Matrix
    53.Maximum Subarray
    基础数据类型包装类
    sqlacodegen逆向数据库
    第四章、常用模块
    第三章、函数编程
    第一章
    第一章 Python基础
    Centos7.0升级python 2.x到3.x
    time
  • 原文地址:https://www.cnblogs.com/ark-blog/p/8729490.html
Copyright © 2011-2022 走看看