gpt4 book ai didi

java - 如何从 Java 发送 html 电子邮件到 outlook

转载 作者:太空狗 更新时间:2023-10-29 22:32:55 26 4
gpt4 key购买 nike

我正在尝试使用 JavaMail 发送 html 格式的电子邮件,但在 Outlook 中它似乎总是只显示为文本电子邮件。

这是我的代码:

try 
{
Properties props = System.getProperties();
props.put("mail.smtp.host", mailserver);
props.put("mail.smtp.from", fromEmail);
props.put("mail.smtp.auth", authentication);
props.put("mail.smtp.port", port);
Session session = Session.getDefaultInstance(props, null);

// -- Create a new message --
MimeMessage message = new MimeMessage(session);

// -- Set the FROM and TO fields --
message.setFrom(new InternetAddress(fromEmail, displayName));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));

MimeMultipart content = new MimeMultipart();
MimeBodyPart text = new MimeBodyPart();
MimeBodyPart html = new MimeBodyPart();

text.setText(textBody);
text.setHeader("MIME-Version" , "1.0" );
text.setHeader("Content-Type" , text.getContentType() );

html.setContent(htmlBody, "text/html");
html.setHeader("MIME-Version" , "1.0" );
html.setHeader("Content-Type" , html.getContentType() );

content.addBodyPart(text);
content.addBodyPart(html);

message.setContent( content );
message.setHeader("MIME-Version" , "1.0" );
message.setHeader("Content-Type" , content.getContentType() );
message.setHeader("X-Mailer", "My own custom mailer");

// -- Set the subject --
message.setSubject(subject);

// -- Set some other header information --
message.setSentDate(new Date());

// INFO: only SMTP protocol is supported for now...
Transport transport = session.getTransport("smtp");
transport.connect(mailserver, username, password);
message.saveChanges();

// -- Send the message --
transport.sendMessage(message, message.getAllRecipients());
transport.close();

return true;

} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
throw e;
}

为什么电子邮件的 html 版本不会在 Outlook 中显示?

最佳答案

经过大量调查,我取得了一些重大进展。

首先,我建议不要直接使用 JavaMail,而是使用 Jakarta Commons Email图书馆。这确实大大简化了问题!

现在的代码是:

HtmlEmail email = new HtmlEmail();

email.setHostName(mailserver);
email.setAuthentication(username, password);
email.setSmtpPort(port);
email.setFrom(fromEmail);
email.addTo(to);
email.setSubject(subject);

email.setTextMsg(textBody);
email.setHtmlMsg(htmlBody);

email.setDebug(true);

email.send();

说的简单。

但是,还有一个问题。电子邮件的 html 版本在 Gmail、Hotmail 等中运行良好。但它仍然无法在 Outlook 中正确显示。它总是想显示文本版本,我不确定为什么。我怀疑这是 Outlook 中的设置,但我找不到它...

关于java - 如何从 Java 发送 html 电子邮件到 outlook,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/322298/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com