3

我已经在此链接上尝试过字符集建议

但是电子邮件显示了 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();

我宁愿不必安装其他方工具.. 这将需要对我当前的代码进行彻底的返工。

4

3 回答 3

2

这是经过测试并确认可以工作的。

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);
}
于 2014-10-08T19:25:01.333 回答
1

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

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

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

于 2012-11-08T22:51:21.467 回答
0

使用Javamail API

这是一个例子

于 2012-11-08T22:51:03.730 回答