Search code examples
javaemailsmtpmime-typesapache-commons

Why does this java mail arrive as plain text instead of html at recipient?


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?


Solution

  • 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)