首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring 整合 Velocity 實現 HTML 郵件模板發送:完整配置與代碼示例

     編輯:Java 綜合教學

Spring 整合 Velocity 實現 HTML 郵件模板發送:完整配置與代碼示例

一、所需 Jar 包依賴

  • velocity-1.7.jar
  • velocity-tools-2.0.jar
  • mail.jar (JavaMail API)
  • spring-context-support-4.0.6.RELEASE.jar (提供 VelocityEngineFactoryBean 等)

二、Spring XML 配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
       xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="https://www.springframework.org/schema/p"
       xmlns:context="https://www.springframework.org/schema/context"
       xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                           https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- Velocity 引擎配置 -->
    <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
        <property name="velocityProperties">
            <props>
                <prop key="resource.loader">file</prop>
                <prop key="file.resource.loader.class">org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader</prop>
                <prop key="file.resource.loader.cache">false</prop>
                <prop key="file.resource.loader.modificationCheckInterval">3</prop>
                <prop key="input.encoding">UTF-8</prop>
                <prop key="output.encoding">UTF-8</prop>
            </props>
        </property>
    </bean>

    <!-- JavaMail 發送器配置 (屬性佔位符從 properties 文件讀取) -->
    <bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="${mail.smtp.host}"/>
        <property name="port" value="${mail.smtp.port}"/>
        <property name="username" value="${mail.smtp.username}"/>
        <property name="password" value="${mail.smtp.password}"/>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
                <prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
                <prop key="mail.smtp.starttls.enable">${mail.smtp.starttls.enable}</prop>
                <prop key="mail.smtp.socketFactory.port">${mail.smtp.port}</prop>
                <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
                <prop key="mail.smtp.socketFactory.fallback">false</prop>
            </props>
        </property>
    </bean>
</beans>

三、郵件發送服務類

package com.ljx.model;

import java.util.HashMap;
import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.velocity.VelocityEngineUtils;

@Component
public class SendTemplateMail {

    @Autowired private JavaMailSenderImpl mailSender;
    @Autowired private VelocityEngine velocityEngine;

    public void sendEmail() throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "GBK");
        helper.setFrom("111111111@qq.com");
        helper.setTo("222222222@qq.com");
        helper.setSubject("測試 HTML 主題");

        // 準備模型數據
        Map<String, Object> model = new HashMap<>();
        model.put("userName", "xxx");

        // 合併模板生成 HTML 內容
        String mailText = VelocityEngineUtils.mergeTemplateIntoString(
                velocityEngine, "mail.vm", "GBK", model);
        System.out.println(mailText);

        helper.setText(mailText, true); // true 表示 HTML 格式
        mailSender.send(message);
    }
}

四、Velocity 模板文件 (mail.vm)

放置於 classpath 根目錄 (如 src/main/resources)。

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>歡迎</h1>
    <div> 您好 ${userName} </div>
</body>
</html>

五、Controller 測試入口

@RequestMapping(value = "/mail.action")
public @ResponseBody String mail() {
    try {
        System.out.println(1);
        mail.sendEmail();
    } catch (MessagingException e) {
        e.printStackTrace();
        return "false";
    }
    return "ok";
}

關鍵點總結

  1. VelocityEngineFactoryBean 配置 ClasspathResourceLoader 從類路徑載入模板。
  2. JavaMailSenderImpl 使用 SSL 連接 (465/587 端口),需設定 SSLSocketFactory。
  3. MimeMessageHelper 簡化 MIME 郵件構建,setText(content, true) 啟用 HTML 模式。
  4. VelocityEngineUtils.mergeTemplateIntoString 將模型數據合併到模板生成最終字串。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved