10X Sale
kh logo
All Courses
  1. Tutorials
  2. Java

Java Mail API

Updated on Sep 2, 2025
 
32,982 Views

In any software application, sending and receiving electronic messages, more specifically e-mails are an essential part. Emails are a medium of communication between different parties who are using the application. In most of the standard programming languages, email APIs are available for communication, and Java is also not an exception. Java provides e-mail APIs which are platform and protocol independent. The mail management framework consists of various abstract classes for defining an e-mail communication system.

In this article, we will discuss about the Java E-mail management framework and its important components. We will also work with some coding examples.

JavaMail Architecture Overview

JavaMail API comes as a default package with java EE platform, and it is optional for java SE platform. Java mail framework is composed of multiple components. JavaMail API is one such component used by the developers to build mail applications. But, these APIs are just a layer between the Java application (mail enabled) and the protocol service providers.

Let us have a look at different layers of Java mail architecture.

  1. JavaMail APIs
    These are the Java interfaces to send and receive e-mails. This layer is completely independent of the underlying protocols.
  2. JavaBeans Activation Framework (JAF)
    This framework is used to manage mail contents like URL, attachments, mail extensions etc.
  3. Service Provider Interfaces
    This layer sits between the protocol implementers and the Java applications, more specifically Java mail APIs. SPIs understand the protocol languages and hence create the bridge between the two sides.
  4. Service protocol implementers
    These are the third party service providers who implements different protocols like SMTP,POP3 and IMAP etc. In this context we must have some ideas on the following protocols.
    a. SMTP
    Simple Mail Transfer Protocol is used for sending e-mails.
    b. POP3
    Post Office Protocol is used to receive e-mails. It provides one to one mapping for users and mail boxes, which is one mail box for one user.
    c. IMAP
    Internet Message Access Protocol is also used to receive e-mails. It supports multiple mail boxes for single user.
    d. MIME
    Multipurpose Internet Mail Extensions is a protocol to define the transferred content.

Following is the Java mail architecture diagram. There are mainly four layers in the system. The top layer is the Java application layer. The second layer is the client API layer along with JAF. Third layer contains server and protocol implementers. And, the bottom layer is the third party service providers.

Java mail architecture

Environment setup Before we start working on the code examples, let us complete the environment setup first. For Java mails, we need to download some JAR files and add them in the CLASSPATH. Following are the two which needs to be installed in your system.

  1. Download JavaMail API and complete the installation
  2. Download JavaBeans Activation Framework (JAF) and install in your system
  3. Add the mail.jar and activation.jar files in your CLASSPATH
  4. Install any SMTP server for sending emails. In our example we will be using Jango SMTP.

Now the environment setup is complete and we will jump into the coding part.

How to send and receive e-mails?

Send Email: In our first example we will check how an email can be sent by using Java mail API and SMTP server. Following are the steps to be followed.

  1. Setup ‘From’ and ‘To’ address along with the user id and password.
  2. Setup SMTP host
  3. Setup properties values
  4. Create session object
  5. Form the message details
  6. Send the message by using Transport object.

This example followed the above steps.

Listing1: Sample code to send emails

import java.util.Properties; 
import javax.mail.Message; 
import javax.mail.MessagingException; 
import javax.mail.PasswordAuthentication; 
import javax.mail.Session; 
import javax.mail.Transport; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeMessage; 
public class DemoSendEmail { 
   public static void main(String[] args) { 
      //Declare recipient's & sender's e-mail id. 
      String destmailid = "destemail@eduonix.com"; 
      String sendrmailid = "frmemail@eduonix.com"; 
     //Mention user name and password as per your configuration 
      final String uname = "username"; 
      final String pwd = "password"; 
      //We are using relay.jangosmtp.net for sending emails 
      String smtphost = "relay.jangosmtp.net"; 
     //Set properties and their values 
      Properties propvls = new Properties(); 
      propvls.put("mail.smtp.auth", "true"); 
      propvls.put("mail.smtp.starttls.enable", "true"); 
      propvls.put("mail.smtp.host", smtphost); 
      propvls.put("mail.smtp.port", "25"); 
      //Create a Session object & authenticate uid and pwd 
      Session sessionobj = Session.getInstance(propvls, 
         new javax.mail.Authenticator() { 
            protected PasswordAuthentication getPasswordAuthentication() { 
               return new PasswordAuthentication(uname, pwd); 
   } 
         }); 
      try { 
   //Create MimeMessage object & set values 
   Message messageobj = new MimeMessage(sessionobj); 
   messageobj.setFrom(new InternetAddress(sendrmailid)); 
   messageobj.setRecipients(Message.RecipientType.TO,InternetAddress.parse(destmailid)); 
   messageobj.setSubject("This is test Subject"); 
   messageobj.setText("Checking sending emails by using JavaMail APIs"); 
  //Now send the message 
   Transport.send(messageobj); 
   System.out.println("Your email is sent successfully...."); 
      } catch (MessagingException exp) { 
         throw new RuntimeException(exp); 
      } 
   } 
}

After compilation and running the application you will get the following output.

Your email is sent successfully….

Receive Email: Now in the second example we will check how to receive emails by using Java Mail APIs.

Please follow the steps below to complete the application

  1. Set up properties values for POP3 server
  2. Create session object
  3. Create POP3 store object and connect
  4. Create folder object and open it
  5. Retrieve email messages and print them in a loop
  6. Close folder and store object

Following code sample follows the steps described above.

Listing2: Sample code to receive emails

import java.util.Properties; 
import javax.mail.Folder; 
import javax.mail.Message; 
import javax.mail.MessagingException; 
import javax.mail.NoSuchProviderException; 
import javax.mail.Session; 
import javax.mail.Store; 
public class DemoCheckEmail{ 
   public static void main(String[] args) { 
     //Set mail properties and configure accordingly 
      String hostval = "pop.gmail.com"; 
      String mailStrProt = "pop3"; 
      String uname = "uname@gmail.com"; 
      String pwd = "password"; 
    // Calling checkMail method to check received emails 
      checkMail(hostval, mailStrProt, uname, pwd); 
   } 
   public static void checkMail(String hostval, String mailStrProt, String uname,String pwd)  
   { 
      try { 
      //Set property values 
      Properties propvals = new Properties(); 
      propvals.put("mail.pop3.host", hostval); 
      propvals.put("mail.pop3.port", "995"); 
      propvals.put("mail.pop3.starttls.enable", "true"); 
      Session emailSessionObj = Session.getDefaultInstance(propvals);   
      //Create POP3 store object and connect with the server 
      Store storeObj = emailSessionObj.getStore("pop3s"); 
      storeObj.connect(hostval, uname, pwd); 
      //Create folder object and open it in read-only mode 
      Folder emailFolderObj = storeObj.getFolder("INBOX"); 
      emailFolderObj.open(Folder.READ_ONLY); 
      //Fetch messages from the folder and print in a loop 
      Message[] messageobjs = emailFolderObj.getMessages();  
      for (int i = 0, n = messageobjs.length; i < n; i++) { 
         Message indvidualmsg = messageobjs[i]; 
         System.out.println("Printing individual messages"); 
         System.out.println("No# " + (i + 1)); 
         System.out.println("Email Subject: " + indvidualmsg.getSubject()); 
         System.out.println("Sender: " + indvidualmsg.getFrom()[0]); 
         System.out.println("Content: " + indvidualmsg.getContent().toString()); 
      } 
      //Now close all the objects 
      emailFolderObj.close(false); 
      storeObj.close(); 
      } catch (NoSuchProviderException exp) { 
         exp.printStackTrace(); 
      } catch (MessagingException exp) { 
         exp.printStackTrace(); 
      } catch (Exception exp) { 
         exp.printStackTrace(); 
      } 
   } 
}

After compiling and running the application you will get the email number, sender details, mail content etc.

Conclusion

Mail communication is a very common feature in any software application. In this article we have discussed the mailing part defined in Java platform. Java has a complete package consisting of APIs for building email enabled applications. But, along with this API layer, third party service providers are also an integral part of Java mailing system. We have also touched a little bit on the architecture side to get an idea how it works internally. And, finally we have worked with two coding examples to demonstrate sending and receiving emails. Hope this tutorial will help you understand Java mailing system in a better way.

+91

By Signing up, you agree to ourTerms & Conditionsand ourPrivacy and Policy

Get your free handbook for CSM!!
Recommended Courses