How to Send Email With Attachment Using JavaMail API

This shows how to send email with an attachment using the JavaMail API with an explanation and example.

About JavaMail API

In Java there are many APIs and JavaMail is one of the APIs used to compose, write and read electronic messages (emails).

JavaMail API provides many facilities and it can be used in many events. It can be applied during the registration of the user (giving acknowledgement for registering or for logging the website to the user's email id), resending the password or sending the notifications related to updates, job alert and so on.

The JavaMail API provides a protocol-independent, platform-independent framework for sending and receiving emails.

There are some packages that we will use in sending the email. The Javax.mail and javax.mail.activation packages contain the core classes along with the javax.mail.internet package is also used since we are sending mail through the internet.

The preceding two packages conatins the core classes and some of the classes are the following:

  • javax.mail.Session class
  • javax.mail.Message class
  • javax.mail.internet.MimeMessage class
  • javax.mail.Address class
  • javax.mail.Authenticator class
  • javax.mail.PasswordAuthentication class
  • javax.mail.internet.InternetAddress class
  • javax.mail.Transport class
  • javax.mail.Store class
  • and so on.

Example of sending email

For sending mail with an attachment, the JavaMail API provides some useful classes like BodyPart, MimeBodyPart, MessageBodyPart and so on.

There are two jar files that play very important roles in sending mail through the JavaMail API and you need to load the jar files.

  • Mail.jar
  • Activation.jar

I had attached these jar files with this article, but you can also download these files from the Oracle website.

Now let's have a look towards the example and understand all the packages and classes.

import javax.mail.*;

import javax.activation.*;

import javax.mail.internet.*;

import java.util.*;

 

class SendAttachment

{

    public static void main(String agrs[])

    {

        String to="[email protected]"; //you can change according to your choice

        final String user="[email protected]"; //you can change according to your choice

        final String password="xxxxxxx"; //you can change according to your choice

 

        Properties properties=System.getProperties(); //getting the session object

        properties.setProperty("mail.smtp.host","mail.c-sharpcorner.com");

        properties.put("mail.smtp.auth","true");

        Session session=Session.getDefaultInstance(properties,new javax.mail.Authenticator()

        {

            protected PasswordAuthentication getPassworAuthentication()

            {

                return new PasswordAuthentication(user,password);

            }

        });

        try

        {

            MimeMessage message= new MimeMessage(session);

            message.setFrom(new InternetAddress(user));

            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            message.setSubject("Message Alert");

            BodyPart messageBodyPart1=new MimeBodyPart(); // creating MimeBodyPart object and set your message text

            messageBodyPart1.setText("This is the message body");

            MimeBodyPart messageBodyPart2=new MimeBodyPart(); // creating new MimeBodyPart object and setting DataHandler to this object

            String filename="SendAttachment.java"; //you can change according to your choice

            DataSource source=new FileDataSource(filename);

            messageBodyPart2.setDataHandler(new DataHandler(source));

            messageBodyPart2.setFileName(filename);

            Multipart multipart=new MimeMultipart(); //creating multipart object and adding MimBodyPart to this object

            multipart.addBodyPart(messageBodyPart1);

            multipart.addBodyPart(messageBodyPart2);

            message.setContent(multipart); //setting multipart object to message object

            Transport.send(message); // sending message

            System.out.println("Message has been sent");

        }

        catch(MessagingException ex){

        ex.printStackTrace();

        }

    }

}   

You can observe the comments in the code that can be treated as the procedure to be followed in sending the mail using the JavaMail API.

Protocols used

There are some protocols that are used in the JavaMail API.

Protocols

There are some other protocols also, like IMAP, SMIME and so on.

Brief explanation of these protocols

SMTP: This is the Simple Mail Transfer Protocol that provides the mechanism to deliver the mail.
POP: This is the Post Office Protocol also known as POP3 that provides the mechanism to receive the mail. It also provides support for the single mail box for each user.
IMAP: This is the Internet Message Access Protocol and also provides mechanism to receive mail with support of multiple mail boxes for each user that can be sharable with multiple users.
MIME: This is the Multiple Internet Mail Extension that tells the browser what is being sent, either attachment, format of the message and so on. It is also known as the mail transfer protocol and is used by your mail program.
NNTP: This is the Network News Transfer Protocol that is responsible for network through which mail is being sent.

Up Next
    Ebook Download
    View all
    Learn
    View all