问题
I have this code to send an email:
public static void sendHtmlTextWithPlainTextAlternative(final String to,
final String from, final String subject, final String plainText,
final String htmlText) throws MessagingException {
final HtmlEmail email = new HtmlEmail();
email.setHostName(SMTP);
try {
email.addTo(getStringAddresses(to));
email.setFrom(from);
email.setSubject(subject);
email.setHtmlMsg("<html><head></head><body><p>Hello World!</p></body></html>");
email.setTextMsg("Hello World!");
email.send();
} catch (final EmailException e) {
e.printStackTrace();
}
}
private static String[] getStringAddresses(final String to) {
return to.split(" |,|;|\\r?\\n|\\r");
}
But all i get in my email client (Outlook 2010) is a plain text message where I can see the html markup and the alternative plain text or a rich text message that is blank (Outlook 2002).
Here is an excerpt
------=_Part_0_756354128.1364993577885
Content-Type: multipart/alternative; boundary="----=_Part_1_48519531.1364993577890"
------=_Part_1_48519531.1364993577890
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
Hello World!
------=_Part_1_48519531.1364993577890
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: 7bit
<html><head></head><body><p>Hello World!</p></body></html>
------=_Part_1_48519531.1364993577890--
------=_Part_0_756354128.1364993577885--
According to one Exchange Server admin the message should contain something like this at the beginning
0 2.1.5 Recipient OK
DATA
354 Start mail input; end with <CRLF>.<CRLF>
Content-Type: multipart/mixed; boundary="----=_Part_1_933059347.1364987366297"
But it arrives like this (excerpt):
250 2.1.5 Recipient OK
DATA
354 Start mail input; end with <CRLF>.<CRLF>
This is the content preamble.
------=_Part_1_933059347.1364987366297
Content-Type: multipart/alternative; boundary="----=_Part_0_1905186593.1364987366295"
The email arrives with an empty subject and an empty recipient list. What could cause this strange behavior?
回答1:
After finding out what to look for the solution was quite simple and I have to thank Cedric Champeau. It was a conflict with geronimo-javamail that was pulled in through another maven dependency. All I had to do was to exclude that dependency: Apache CXF + Maven + Javamail + Log4J (update)
回答2:
I see your using apache commons?
Try removing the head and body tag
So you will have
email.setHtmlMsg("<html><p>Hello World!</p></html>");
Another thing that should not make a difference but you can try is setting correct valur for email.setHostName("mail.myserver.com");
Ref commons eml user guide
And send the mail to a gmail account, maybe the server has a setting to only allow text and its removing html? Can you send the same mail id html from gmail (rich formatting) ?
来源:https://stackoverflow.com/questions/15786239/why-does-this-java-mail-arrive-as-plain-text-instead-of-html-at-recipient