采用velocity模板引擎作为Java邮件模板

本文介绍了一种使用Java实现的邮件模板生成及发送方法。通过Velocity模板引擎填充个性化内容,并利用JavaMail API完成邮件发送。文章详细展示了如何设置邮件内容、配置SMTP服务器等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     获取邮件模板

public String getMailContent(String name, String tel) throws IOException {
    StringWriter stringWriter = new StringWriter();
    // velocity引擎
    VelocityEngine velocityEngine = new VelocityEngine();
    // 设置文件路径属性
    Properties properties = new Properties();
    String dir = this.getClass().getResource("/").getPath();
    properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, dir + "static/template/");
    // 引擎初始化属性配置
    velocityEngine.init(properties);
    // 加载指定模版
    Template template = velocityEngine.getTemplate("userInfo.vm", "utf-8");
    // 填充模板内容
    VelocityContext velocityContext = new VelocityContext();
    velocityContext.put("name", name);
    velocityContext.put("tel", tel);
    // 写到模板
    template.merge(velocityContext, stringWriter);
    return stringWriter.toString();
}


     发送邮件

public static void doSend(String name,String tel,String subject)
        throws UnsupportedEncodingException, MessagingException {
    JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
    senderImpl.setHost(host);
    senderImpl.setUsername(username);
    senderImpl.setPassword(password);
    MimeMessage mailMessage = senderImpl.createMimeMessage();
    MimeMessageHelper message = new MimeMessageHelper(mailMessage, true, "utf-8");
    message.setFrom(new InternetAddress(MimeUtility.encodeText(from, "utf-8", null)
            + " <" + fromAddress + ">"));
    message.setTo(to);
    message.setSubject(subject);
    message.setText(getMailContent(name,tel), true);
    Properties prop = new Properties();
    prop.put("mail.smtp.auth", "false"); // smtp不需要认证
    prop.put("mail.smtp.port", port);
    prop.put("mail.smtp.timeout", 60000); // 超时
    senderImpl.setJavaMailProperties(prop);
    senderImpl.send(mailMessage);
}


    在模板文件中使用$符获取:

<tr>
    <td style="padding: 70px 0 0 185px">
        <span style="font-size:14px">Hi,$name</span>
    </td>
</tr>


<tr>
    <td style="padding: 12px 0 70px 185px">
        <span style="font-size:14px">$tel</span>
    </td>
</tr>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值