Search code examples
javaversionjakarta-mailapache-commons-email

org.apache.commons.mail.MultiPartEmail sends email with empty body


Sending email org.apache.commons.mail.MultiPartEmail.send() sends email with empty body. I have tried with commons-email 1.2, 1.3.1, 1.3.3. Java 1.7.0_55 was the earliest version which caused the empty email body.


Solution

  • According to http://www.oracle.com/technetwork/java/javase/7u55-relnotes-2177812.html#knownissues-7u55 After initialization of SAAJ components, the javax.mail library may fail to work under certain circumstances, which in turn could break the javax.mail's JAF setup. A possible workaround is to re-add the javax.mail handler before using javax.mail API:

    MailcapCommandMap mailMap = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
    mailMap.
        addMailcap("multipart/mixed;;x-java-content-handler=com.sun.mail.handlers.multipart_mixed");"
    

    Calling new AttachmentPartImpl(); is one of the certain circumstances.

    In the application

    com.sun.xml.internal.messaging.saaj.soap.MessageImpl.createAttachmentPart()
    

    is called before sending the email. It does nothing else but return new AttachmentPartImpl(); which contains headers = new MimeHeaders(); Calling new MimeHeaders() was not enough for empty body to occur. Calling new AttachmentPartImpl(); before sending the mail resulted empty body. Re-adding the javax.mail handler before using javax.mail API solved the problem.

    MultiPartEmail email = new MultiPartEmail();
    email.setHostName(smtpServer);
    email.addTo(to);
    email.setFrom(from);
    email.setSubject(subject);
    email.setMsg(msg);
    email.setSocketTimeout(20000);
    email.setSocketConnectionTimeout(20000);
    // SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
    // soapMessage.createAttachmentPart(); // enough for empty body
    new AttachmentPartImpl(); // enough for empty body
    // new MimeHeaders(); not enough for empty body
    email.send();