?
本文檔使用 php中文網(wǎng)手冊(cè) 發(fā)布
org.springframework.mail.javamail.MimeMessageHelper
是處理JavaMail郵件時(shí)比較順手組件之一。它可以讓你擺脫繁復(fù)的JavaMail API。
通過(guò)使用MimeMessageHelper
,創(chuàng)建一個(gè)MimeMessage
實(shí)例將非常容易:
// of course you would use DI in any real-world cases
JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setHost("mail.host.com");
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setTo("test@host.com");
helper.setText("Thank you for ordering!");
sender.send(message);
Multipart email允許添加附件和內(nèi)嵌資源(inline resources)。內(nèi)嵌資源可能是你在信件中希望使用的圖像或樣式表,但是又不想把它們作為附件。
下面的例子將展示如何使用MimeMessageHelper
來(lái)發(fā)送一封email,使用一個(gè)簡(jiǎn)單的JPEG圖片作為附件:
JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost("mail.host.com"); MimeMessage message = sender.createMimeMessage(); // use the true flag to indicate you need a multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo("test@host.com"); helper.setText("Check out this image!"); // let's attach the infamous windows Sample file (this time copied to c:/) FileSystemResource file = new FileSystemResource(new File("c:/Sample.jpg")); helper.addAttachment("CoolImage.jpg", file); sender.send(message);
下面的例子將展示如何使用MimeMessageHelper
來(lái)發(fā)送一封含有內(nèi)嵌資源的email:
JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost("mail.host.com"); MimeMessage message = sender.createMimeMessage(); // use the true flag to indicate you need a multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo("test@host.com"); // use the true flag to indicate the text included is HTML helper.setText("<html><body><img src='cid:identifier1234'></body></html>", true); // let's include the infamous windows Sample file (this time copied to c:/) FileSystemResource res = new FileSystemResource(new File("c:/Sample.jpg")); helper.addInline("identifier1234", res); sender.send(message);
如你所見(jiàn),嵌入式資源使用Content-ID
(上例中是identifier1234
)來(lái)插入到mime信件中去。你加入文本和資源的順序是非常重要的。首先,你加入文本,隨后是資源。如果順序弄反了,它將無(wú)法正常運(yùn)作!
在之前的代碼示例中,所有郵件的內(nèi)容都是顯式定義的,并通過(guò)調(diào)用message.setText(..)
來(lái)設(shè)置郵件內(nèi)容。
這種做法針對(duì)簡(jiǎn)單的情況或在上述的例子中沒(méi)什么問(wèn)題,因?yàn)樵谶@里只是為了向你展示基礎(chǔ)API。
而在你自己的企業(yè)級(jí)應(yīng)用程序中, 基于如下的原因,你不會(huì)以上述方式創(chuàng)建你的郵件內(nèi)容:
使用Java代碼來(lái)創(chuàng)建基于HTML的郵件內(nèi)容不僅容易犯錯(cuò),同時(shí)也是一件單調(diào)乏味的事情
這樣做,你將無(wú)法將顯示邏輯和業(yè)務(wù)邏輯很明確的區(qū)分開(kāi)
一旦需要修改郵件內(nèi)容的顯式格式和內(nèi)容,你需要重新編寫(xiě)Java代碼,重新編譯,重新部署……
一般來(lái)說(shuō)解決這些問(wèn)題的典型的方式是使用FreeMarker或者Velocity這樣的模板語(yǔ)言來(lái)定義郵件內(nèi)容的顯式結(jié)構(gòu)。 這樣,你的任務(wù)就是在你的代碼中,只要?jiǎng)?chuàng)建在郵件模板中需要展示的數(shù)據(jù),并發(fā)送郵件即可。通過(guò)使用Spring對(duì)FreeMarker和Velocity的支持類, 你的郵件內(nèi)容將變得簡(jiǎn)單,這同時(shí)也是一個(gè)最佳實(shí)踐。下面是一個(gè)使用Velocity來(lái)創(chuàng)建郵件內(nèi)容的例子:
使用Velocity來(lái)創(chuàng)建你的郵件模板,你需要把Velocity加入到classpath中。 同時(shí)要根據(jù)應(yīng)用的需要為郵件內(nèi)容創(chuàng)建一個(gè)或者多個(gè)Velocity模板。下面的Velocity模板是這個(gè)例子中所使用的基于HTML的模板。 這只是一個(gè)普通的文本,你可以通過(guò)各種其他的編輯器來(lái)編輯該文本,而無(wú)需了解Java方面的知識(shí)。
# in the com/foo/package
<html>
<body>
<h3>Hi ${user.userName}, welcome to the Chipping Sodbury On-the-Hill message boards!</h3>
<div>
Your email address is <a href="mailto:${user.emailAddress}">${user.emailAddress}</a>.
</div>
</body>
</html>
下面提供了一些簡(jiǎn)單的代碼與Spring XML配置,它們使用了上述Velocity模板來(lái)創(chuàng)建郵件內(nèi)容并發(fā)送郵件。
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); } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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"> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="mail.csonth.gov.uk"/> </bean> <bean id="registrationService" class="com.foo.SimpleRegistrationService"> <property name="mailSender" ref="mailSender"/> <property name="velocityEngine" ref="velocityEngine"/> </bean> <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean"> <property name="velocityProperties"> <value> resource.loader=class class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader </value> </property> </bean> </beans>