如何发送HTML电子邮件?

问题描述:

我已经使用JMS在我的Web应用程序中成功发送电子邮件,但结果只显示在纯文本中。我希望内容能够显示html。我该怎么做?这大概是我有的:

I have successfully sent email in my web application using JMS, but the result only displays in plain text. I want the content to be able to display html. How do I do it? Here is roughly what I have:

Message msg = new MimeMessage(mailSession);
try{
    msg.setSubject("Test Notification");
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(sentTo, false));
    String message = "<div style=\"color:red;\">BRIDGEYE</div>";
    msg.setContent(message, "text/html; charset=utf-8");
    msg.setSentDate(new Date());
    Transport.send(msg);
}catch(MessagingException me){
    logger.log(Level.SEVERE, "sendEmailNotification: {0}", me.getMessage());
}


根据Javadoc, MimeMessage#setText() 设置默认的mime类型 text / plain ,而您需要 text / html的。而是使用 MimeMessage#setContent()

As per the Javadoc, the MimeMessage#setText() sets a default mime type of text/plain, while you need text/html. Rather use MimeMessage#setContent() instead.

message.setContent(someHtmlMessage, "text/html; charset=utf-8");

请注意,HTML不应包含< html> < head> < body> 。 Gmail会忽略它。另请参见邮件客户端中的CSS支持

Note that the HTML should not contain the <html>, <head> or <body>. Gmail will ignore it. See also CSS support in mail clients.