Learn How to use Java Mail API to send and receive emails

7
22257
Mail, email, marketing

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 the Java E-mail management framework and its important components. We will also work with some coding examples.

JavaMail architecture overview
Java mail API comes as a default package with Java EE platform, and it is optional for the 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.
Java Mail APIs: These are the Java interfaces to send and receive e-mails. This layer is completely independent of the underlying protocols.
JavaBeans Activation Framework (JAF): This framework is used to manage mail contents like URL, attachments, mail extensions etc.
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.
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.

  • SMTPSimple Mail Transfer Protocol is used for sending e-mails.
  • POP3 Post Office Protocol is used to receive e-mails. It provides one to one mapping for users and mailboxes, which is one mailbox for one user.
  • IMAP Internet Message Access Protocol is also used to receive e-mails. It supports multiple mailboxes for a single user.
  • 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. The third layer contains server and protocol implementers. And, the bottom layer is the third party service providers.

Image1

Image1: Java Mail system architecture diagram

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 to the CLASSPATH. The following are the two which need to be installed in your system.

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

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. The following are the steps to be followed.

  • Setup ‘From’ and ‘To’ address along with the user id and password.
  • Setup SMTP host
  • Setup properties values
  • Create a session object
  • Form the message details
  • Send the message by using the Transport object.

The following listing 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 = "[email protected]";
      String sendrmailid = "[email protected]";	  
     //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 sent successfully....");
      } catch (MessagingException exp) {
         throw new RuntimeException(exp);
      }
   }
}

After compilation and running the application you will get the following output.
Your email 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

  • Set up properties values for POP3 server
  • Create a session object
  • Create a POP3 store object and connect
  • Create a folder object and open it
  • Retrieve email messages and print them in a loop
  • Close folder and store object

The 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 = "[email protected]";
      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 the 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 the Java mailing system. We have also touched a little bit on the architecture side to get an idea of 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.

7 COMMENTS

  1. Hi Sabeer,
    Your article is great tutorial for me and other users. But your tutorial is really amazing and informative. I would say you’ve done a great job with this.
    Thanks to share this precious tutorial with us

  2. Hello sir can you post a code which receive only unread recent mail with attachment. because through the above code i am getting all mails and attachment which is available in existing mail.

  3. Hey Thank you for helping me, can i get the Email App in android Studio(with inbox Activity,SendActivity,ComposeActivity ) for my project reference ,

LEAVE A REPLY

Please enter your comment!
Please enter your name here