Send E-mail with attachments using JavaMail


As I promised in my earlier post ‘Send E-mail using JavaMail API and your GMail account’ I’ll show you how to send an email with an attachment using JavaMail API (http://java.sun.com/products/javamail).

Basic steps are similar to my previous post . So before proceed with this one, I recommend you to refer my previous article, in order to get a basic idea.

If you need to send an email with an attachment, first you need to construct a MimeMultipart message. MimeMultipart message is composed of MimeBodyPart messages. You can attach your file in to MimeBodyPart message and then MimeBodyPart can be further added to MimeMultipart message. Finally MimeMultipart message can be added to basic MimeMessage by calling its setContent (MimeMultipart message) method.

This relationship is illustrated below.

Hierarchical view of different messages
Hierarchical view of different messages

You can download the complete source code for the application here

Advertisements