如何从 Java 向 Outlook 发送 html 电子邮件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/322298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 13:10:14  来源:igfitidea点击:

How to send html email to outlook from Java

javaemailjavamail

提问by Stephane Grenier

I'm trying to send an email in html format using JavaMail but it always seems to only display as a text email in Outlook.

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

Here is my code:

这是我的代码:

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;
}       

Any ideas why the html version of the email won't display in Outlook?

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

采纳答案by Stephane Grenier

After a lot of investigation, I've been able to make some significant progress.

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

Firstly, instead of using JavaMail directly, I recommend using the Jakarta Commons Emaillibrary. This really simplifies the issue a lot!

首先,我建议使用Jakarta Commons Email库,而不是直接使用 JavaMail 。这真的把问题简化了很多!

The code is now:

现在的代码是:

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();

Talk about simple.

谈简单。

However, there is still an issue. The html version of the email works great in Gmail, Hotmail, etc. But it still won't correctly display in Outlook. It always wants to display the text version and I'm not sure why. I suspect it's a setting in Outlook, but I can't find it...

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

回答by Ken Gentle

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

setContentand setHeader("Content-Type", String)do the same thing - is it possible that html.getContentType()is returning something other than text/html?

setContentsetHeader("Content-Type", String)做同样的事情 - 是否有可能html.getContentType()返回除text/html?

Expanding based on comment and @PhilLho & @erickson's answer (geez, I must type slowly), use:

根据评论和@PhillLho 和@erickson 的回答进行扩展(天啊,我必须慢慢输入),使用:

MimeMultipart content = new MimeMultipart("alternative")

回答by PhiLho

You should look at the source of the received message: is the Content-Type of the message multipart/alternative?

您应该查看收到的消息的来源:消息的 Content-Type 是否是多部分/替代的?

回答by erickson

In addition to removing the html.setHeader("Content-Type", html.getContentType())call as suggest already, I'd replace the line:

除了html.setHeader("Content-Type", html.getContentType())按照建议删除电话之外,我还要替换以下行:

MimeMultipart content = new MimeMultipart();

…with:

…和:

MimeMultipart content = new MimeMultiPart("alternative");

…and removing the line:

...并删除该行:

message.setHeader("Content-Type" , content.getContentType() );

The default MimeMultiPart constructor could be causing problems with a "multipart/mixed" content-type.

默认的 MimeMultiPart 构造函数可能会导致“多部分/混合”内容类型出现问题。

When using multipart/alternative, the alternatives are ordered by how faithful they are to the original, with the best rendition last. However, clients usually give users an option to display plain text, even when HTML is present. Are you sure that this option is not enabled in Outlook? How do other user agents, like Thunderbird, or GMail, treat your messages?

当使用 multipart/alternative 时,替代品按照它们对原版的忠实程度排序,最好的演绎在最后。但是,客户端通常会为用户提供显示纯文本的选项,即使存在 HTML 也是如此。您确定未在 Outlook 中启用此选项吗?其他用户代理(如 Thunderbird 或 GMail)如何处理您的邮件?

Also, ensure that the HTML is well-formed. I'd validate the HTML content with the W3 validation service, and possibly save it into a file and view it with different versions of IE too. Maybe there's a flaw there causing Outlook to fall back to plain text.

此外,请确保 HTML 格式正确。我会使用W3 验证服务验证 HTML 内容,并可能将其保存到文件中并使用不同版本的 IE 进行查看。也许有一个缺陷导致 Outlook 回退到纯文本。

回答by Stephane Grenier

workaroung solution solved outlook 2003: This message uses a character set that is not supported by the Internet Service. doesn't display correctly.

workaroung 解决方案解决了 Outlook 2003:此消息使用了 Internet 服务不支持的字符集。显示不正确。

It could be due to the encoding. Most html pages use iso-8859-1 not cp-1252 try changing

这可能是由于编码。大多数 html 页面使用 iso-8859-1 而不是 cp-1252 尝试更改

For example, your code is:

例如,您的代码是:

message.setContent(sBuffer.toString(), "text/html");

Change this to:

将此更改为:

message.setContent(new String(sBuffer.toString().getBytes(), "iso-8859-1"), "text/html; charset=\"iso-8859-1\"");

This throws a new checked exception : java.io.UnsupportedEncodingException so you need to declare it to be thrown or catch it. iso-8859-1 is supported so, the exception will never be thrown unless something gets corrupted with your rt.jar.

这会抛出一个新的检查异常:java.io.UnsupportedEncodingException 所以你需要声明它被抛出或捕获它。支持 iso-8859-1,因此永远不会抛出异常,除非您的 rt.jar 损坏了某些内容。

Regards, Javeed [email protected]

问候, Javeed [email protected]

回答by user225486

Change this To:

将此更改为:

message.setContent(new String(sBuffer.toString().getBytes(), "iso-8859-1"), "text/html; charset=\"iso-8859-1\"");

The content char set need to be set, I don't see why the content itself. Should rather be:

需要设置内容字符集,我不明白为什么内容本身。应该是:

message.setContent(sBuffer.toString(), "text/html;charset=iso-8859-1");

回答by Kuldeep

message.setContent(new String(sBuffer.toString().getBytes(), "iso-8859-1"), "text/html; charset=iso-8859-1");

Should solve your problem (removed \"characters).

应该可以解决您的问题(删除\"字符)。

回答by AVA

I used the following code:

我使用了以下代码:

mimeBodyPart1.setDataHandler(new DataHandler(new ByteArrayDataSource(messageBody, "text/html; charset=utf-8")));
multiPart.addBodyPart(mimeBodyPart1);
message.setContent(multiPart, "text/html; charset=utf-8");

Now, Outlookdisplays in htmlformat.

现在,Outlookhtml格式显示。