19.2.2 发送富文本内容的 Email

发送富文本的 Email 与发送简单文本的 Email 并没有太大区别。关键是将消息的文本设置为 HTML。要做到这一点只需将 HTML 字符串传递给 helper 的 setText() 方法,并将第二个参数设置为 true:

helper.setText("<html><body><img src='cid:spitterLogo'>" +
  "<h4>" + spittle.getSpitter().getFullName() + " says...</h4>" +
  "<i>" + spittle.getText() + "</li>" +
  "</body></html>", true);

第二个参数表明传递进来的第一个参数是 HTML,所以需要对消息的内容类型进行相应的设置。

要注意的是,传递进来的 HTML 包含了一个 <img> 标签,用来在 Email 中展现 Spittr 应用程序的 logo。src 属性可以设置为标准的 “http:” URL,以便于从 Web 中获取 Spittr 的 logo。但在这里,我们将 logo 图片嵌入在了 Email 之中。值 “cid:spitterLogo” 表明在消息中会有一部分是图片并以 spitterLogo 来进行标识。

为消息添加嵌入式的图片与添加附件很类似。不过这次不再使用 helper 的 addAttachment() 方法,而是要调用 addInline() 方法:

ClassPathResource image = new ClassPathResource("spitter_logo_50.png");
helper.addInline("spitterLogo", image);

addInline 的第一个参数表明内联图片的标识符 —— 与 <img> 标签的 src 属性所指定的相同。第二个参数是图片的资源引用,这里使用 ClassPathResource 从应用程序的类路径中获取图片。

除了 setText() 方法稍微不同以及使用了 addInline() 方法以外,发送含有富文本内容的 Email 与发送带有附件的普通文本消息很类似。为了进行对比,以下是新的 sendRichSpitterEmail() 方法。

public void sendRichSpitterEmail(String to, Spittle spittle) throws MessagingException {
  MimeMessage message = mailSender.createMimeMessage();
  MimeMessageHelper helper = new MimeMessageHelper(message, true);
  helper.setFrom("noreply@spitter.com");
  helper.setTo("craig@habuma.com");
  helper.setSubject("New spittle from " + spittle.getSpitter().getFullName());
  helper.setText ("<html><body><img src='cid: spitterLogo'>" +
    "<h4>" + spittle.getSpitter().getFullName() + " says...</h4>" +
    "<i>" + spittle.getText() + "</i>" +
    "</body></html>", true);
  ClassPathResource image = new ClassPathResource("spitter_logo_50.png");
  helper.addlnline("spitterLogo", image);
  mailSender.send(message);
}

现在你发送的 Email 带有富文本内容和嵌入式图片了!你可以到此为止并完全结束你的 Email 代码。但创建 Email 体时,使用字符串拼接的办法来构建 HTML 消息依旧让我觉得美中不足。在结束 Email 话题之前,让我们看看如何用模板来代替字符串拼接消息。

Last updated