如何使用JavaMail发送HTML电子邮件?

时间:2012-11-08 22:41:55

标签: java html email smtp mime

我已经在this link

尝试了charset建议

但是电子邮件显示的是messageText的确切值...没有呈现任何HTML。

这是我目前的代码

import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

String messageText = "<br/>THIS IS A TEST...<br/>!!!";

Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.auth", "true"); 
props.setProperty("mail.smtp.ssl.enable", "true");

Session mailSession = Session.getInstance(props, null);
mailSession.setDebug(true);
Transport transport = mailSession.getTransport();

MimeMessage message = new MimeMessage(mailSession);
message.setSubject(messageSubject);
message.setContent(messageText, "text/html; charset=utf-8");

Address[] fromAddress = InternetAddress.parse ( "pleasedonotreplymessage@[removed]" ) ; 
message.addFrom( fromAddress );

message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));

transport.connect("[removed]", "", "");
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();

我希望必须安装其他方工具..这需要对我当前的代码进行彻底的修改。

3 个答案:

答案 0 :(得分:1)

您可以使用Thymeleaf呈现丰富的HTML电子邮件,并使用Spring Mail实用程序发送它。

教程:http://www.thymeleaf.org/doc/articles/springmail.html

教程源代码:https://github.com/thymeleaf/thymeleafexamples-springmail

答案 1 :(得分:1)

经过测试并确认无效。

HTML电子邮件有更多优雅的结构可供更广泛的电子邮件客户端支持,但是对于快速解决方案,这适用于我测试的读者(Outlook,连接到Exchange的Android邮件客户端)和Gmail)。

public static void sendHtmlEmail(String server, String from, String to, String cc, String subject, String htmlBody) throws MessagingException {
    Properties props = new Properties();
    props.setProperty("mail.smtp.host", server);
    Session session = Session.getInstance(props);

    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(from);
    msg.setRecipients(RecipientType.TO, to);
    msg.setRecipients(RecipientType.CC, cc);
    msg.setSubject(subject);
    msg.setSentDate(new Date());

    MimeMultipart mp = new MimeMultipart();
    MimeBodyPart part = new MimeBodyPart();
    part.setText(htmlBody);
    mp.addBodyPart(part);
    msg.setContent(mp);

    // Content type has to be set after the message is put together
    // Then saveChanges() must be called for it to take effect
    part.setHeader("Content-Type", "text/html");
    msg.saveChanges();

    Transport.send(msg);
}

答案 2 :(得分:0)