mimemessage类是什么_使用MimeMessageHelper

22.3.2.1. 一个基于Velocity的示例

使用Velocity来创建你的邮件模板,你需要把Velocity加入到classpath中。

同时要根据应用的需要为邮件内容创建一个或者多个Velocity模板。下面的Velocity模板是这个例子中所使用的基于HTML的模板。

这只是一个普通的文本,你可以通过各种其他的编辑器来编辑该文本,而无需了解Java方面的知识。

# in the com/foo/package

Hi ${user.userName}, welcome to the Chipping Sodbury On-the-Hill message boards!

Your email address is ${user.emailAddress}.

下面提供了一些简单的代码与Spring XML配置,它们使用了上述Velocity模板来创建邮件内容并发送邮件。

package com.foo;

import org.apache.velocity.app.VelocityEngine;

import org.springframework.mail.javamail.JavaMailSender;

import org.springframework.mail.javamail.MimeMessageHelper;

import org.springframework.mail.javamail.MimeMessagePreparator;

import org.springframework.ui.velocity.VelocityEngineUtils;

import javax.mail.internet.MimeMessage;

import java.util.HashMap;

import java.util.Map;

public class SimpleRegistrationService implements RegistrationService {

private JavaMailSender mailSender;

private VelocityEngine velocityEngine;

public void setMailSender(JavaMailSender mailSender) {

this.mailSender = mailSender;

}

public void setVelocityEngine(VelocityEngine velocityEngine) {

this.velocityEngine = velocityEngine;

}

public void register(User user) {

// Do the registration logic...

sendConfirmationEmail(user);

}

private void sendConfirmationEmail(final User user) {

MimeMessagePreparator preparator = new MimeMessagePreparator() {

public void prepare(MimeMessage mimeMessage) throws Exception {

MimeMessageHelper message = new MimeMessageHelper(mimeMessage);

message.setTo(user.getEmailAddress());

message.setFrom("webmaster@csonth.gov.uk"); // could be parameterized...

Map model = new HashMap();

model.put("user", user);

String text = VelocityEngineUtils.mergeTemplateIntoString(

velocityEngine, "com/dns/registration-confirmation.vm", model);

message.setText(text, true);

}

};

this.mailSender.send(preparator);

}

}

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

resource.loader=class

class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值