Does JavaMail support creation of mail with nested MimeMultiParts?

Matt Newberry


To add a file attachment to multipart/alternative email (plain part + html part), I need to create the "alternative" MimeMultiPart, adding the plain and html Parts to it; then create a "mixed" MimeMultiPart, adding both the alternative multipart and the file attachment Parts to it. The MultiPart.addBodyPart() method does not support adding another MultiPart.
The solution is the create both an "alternative" MimeMultipart and a "mixed" MimeMultipart. Add the "plain" and "html" MimeBodyParts to the alternative MimeMultipart. Then create an empty MimeBodyPart and call it's setContent() method, passing in the alternative MimeMultipart. Now add that MimeBodyPart to the mixed MimeMultipart and, finally, add any attachments as additional mixed MimeBodyParts.

Whew! Describing it is more labor than doing it. Maybe this code snippet will make it clearer:

Message msg;
MimeBodyPart plainPart = new MimeBodyPart();
MimeBodyPart htmlPart = new MimeBodyPart();
Vector attachments = new Vector();

private void buildMessage() throws MessagingException {
    Multipart alt = new MimeMultipart("alternative");
    if (attachments.size() == 0)
    else {
        Multipart mixed = new MimeMultipart("mixed");
        MimeBodyPart wrap = new MimeBodyPart();
        wrap.setContent(alt);    // HERE'S THE KEY
        Enumeration att = attachments.elements();
        while (att.hasMoreElements()) {
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact