Spring郵件發送2

前言:上一篇博文講解了郵件發送的基礎用法(數據是寫死的),然而在實際開發中,大多數狀況下郵件內容都是根據業務來動態生成的。因此在此篇博文中,咱們將講解郵件發送攜帶數據的幾種方案。html

 

1、解析自定義佔位符spring

  實現方法: 經過解析自定義佔位符,將傳遞到郵件中的數據,轉換成html內容,進行發送。apache

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-Caseui

// 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);

 

 

2、使用Velocity模板spa

  實現方法:借用VelocityEngineUtils合併Velocity模板和數據,獲得要發送的Email, 進行發送。code

1) 引入依賴jar包orm

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

 

2) 配置Velocity模板引擎htm

<!-- 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) 發送郵件實現函數blog

// 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);

 

 

3、使用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);
相關文章
相關標籤/搜索