22.4. 使用 JavaMail MimeMessageHelper

Spring Framework

22.4. 使用 JavaMail MimeMessageHelper

org.springframework.mail.javamail.MimeMessageHelper是处理JavaMail邮件常用的顺手组件之一。它可以让你摆脱繁复的javax.mail.internetAPI类。下面是一些通常的场景:

22.4.1. 创建一条简单的MimeMessage,并且发送出去

使用MimeMessageHelper来创建和发送 MimeMessage消息是非常容易的:

// 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("[email protected]");
helper.setText("Thank you for ordering!");

sender.send(message);

22.4.2. 发送附件和嵌入式资源(inline resources)

Email允许添加附件,也允许在multipart信件中内嵌资源。内嵌资源可能是你在信件中希望使用的图像,或者样式表,但是又不想把它们作为附件。下面的例子演示如何使用MimeMessageHelper来发送带有内嵌图像的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("[email protected]");

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

// if you would need to include the file as an attachment, use
// the various addAttachment() methods on the MimeMessageHelper

sender.send(message);

警告

如你所见,嵌入式资源使用Content-ID(上例中是identifier1234)来插入到mime信件中去。你加入文本或者资源的顺序是非常重要的。首先,你加入文本,随后是资源。如果你弄反了顺序,它将无法正常运作!