How to Send Email With Attachment Using JavaMail API

About JavaMail API

In Java there are many APIs and JavaMail is one of the APIs which is 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 logging website to user’s email id), resending the password or sending the notifications related to updates, job alert, etc.

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

There are some packages which we are going to use in sending the email. Javax.mail and javax.mail.activation packages contains the core classes along with javax.mail.internet package also used since we are sending mail through internet.

The above two packages conatins the core classes and some of the classes are as 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 etc.

Example of sending email

For sending mail with attachment, JavaMail API provides some useful classes like BodyPart, MimeBodyPart, MessageBodyPart, etc.

There are two jar files which plays very important role in sending mail through JavaMail API and you have 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 Oracle website.

Now let’s have a look towards the example and understand all the packages, 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 coding that can be treated as the steps followed in sending the mail using JavaMail API.

Protocols used

There are some protocols which are used in JavaMail API.

Protocols

There are some other protocols also like IMAP, SMIME, etc.

Brief explanation of these protocols

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

Up Next
    Ebook Download
    View all
    Learn
    View all