JavaMail API - Sending Email With Attachment

Here is an example to send an email with attachment from your machine. The file on local machine is file.txt placed at /home/manisha/. Here we have used JangoSMPT server via which emails are sent to our destination email address. The setup is explained in the Environment Setup chapter.

To send a email with an inline image, the steps followed are:

Get a Session

Create a default MimeMessage object and set From,To,Subject in the message.

Set the actual message as below:

messageBodyPart.setText("This is message body");

Create a MimeMultipart object. Add the above messageBodyPart with actual message set in it, to this multipart object.

As we are using the SMTP server provided by the host provider JangoSMTP, we need to authenticate the username and password. The javax.mail.PasswordAuthentication class is used to authenticate the password.

Compile and Run

Now that our class is ready, let us compile the above class. I've saved the class SendAttachmentInEmail.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt: