Friday, January 25, 2013

JavaMail Quirk

While creating a fairly simple program recently, I stumbled upon some odd behavior with the latest release of the JavaMail API (1.4.5).  OK, maybe its not that odd, but it seems different from how I remember things.

Basically, one of the requirements for the program is to send emails with file attachments.  No real text is required within the email body.  It should be no surprise that I'm using the Spring Framework for this project, and as such I am using the MimeMessageHelper to create my message and then send it.

The issue arises when I try to send an email without any body text.  In this case, here is the error that I see:

org.springframework.mail.MailSendException: Failed messages: javax.mail.MessagingException: IOException while sending message;
  nested exception is:
      java.io.IOException: javax.mail.MessagingException: Empty multipart: multipart/related;
      boundary="----=_Part_1_30254491.1359131496129"; message exceptions (1) are:
Failed message 1: javax.mail.MessagingException: IOException while sending message;
  nested exception is:
      java.io.IOException: javax.mail.MessagingException: Empty multipart: multipart/related;
      boundary="----=_Part_1_30254491.1359131496129"

Not very informative, is it?

After doing some research (aka lots of googling), I found out that the MIME spec apparently does not allow multi-part messages with no body parts (see javadoc).

There are two ways to get around this:
  • Simply add some text to the body of the message (easy)
  • Turn off this restriction which prevents empty messages
Fortunately, if your requirements dictate an email with no body, you can change the default behavior by setting a system property:

System.setProperty("mail.mime.multipart.allowempty", "true");

Hope this helps someone save some time in the future...


1 comment:

  1. This post really saved me a lot of headache. Thank you Ted !!!!!!

    ReplyDelete