View RSS Feed

Java Mail

Email Multi-Part Messages

Rate this Entry
by , 04-25-2012 at 09:33 PM (1456 Views)
Message could be sent with text, HTML message body or file attachment by using multi part messages. MimeMultipart object can be created to hold parts, then MimeBodyPart objects are created for every attachment/ message body and added to container. Lastly, container is assigned to MimeMessage content.

Java Code:
import javax.activation.DataHandler;
import javax.mail.Multipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;

// ...
        String htmlBody;        // ...
        byte[] attachmentData;  // ...

        Multipart mp = new MimeMultipart();

        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(htmlBody, "text/html");
        mp.addBodyPart(htmlPart);

        MimeBodyPart attachment = new MimeBodyPart();
        attachment.setFileName("manual.pdf");
        attachment.setContent(attachmentData, "application/pdf");
        mp.addBodyPart(attachment);

        message.setContent(mp);
For security purposes, message parts and attachments must be of one of several allowed types, and attachment filenames must end in a recognized filename extension for the type.

Submit "Email Multi-Part Messages" to Facebook Submit "Email Multi-Part Messages" to Digg Submit "Email Multi-Part Messages" to del.icio.us Submit "Email Multi-Part Messages" to StumbleUpon Submit "Email Multi-Part Messages" to Google

Comments