top

Search

Java Tutorial

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 Java mail 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. 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. SMTP– Simple 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 mail boxes, which is one mail box for one user. IMAP– Internet Message Access Protocol is also used to receive e-mails. It supports multiple mail boxes for 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. Third layer contains server and protocol implementers. And, the bottom layer is the third party service providers. 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. Download JavaMail API 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 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. Setup ‘From’ and ‘To’ address along with the user id and password. Setup SMTP host Setup properties values Create session object Form the message details 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 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 session object Create POP3 store object and connect Create folder object and open it Retrieve email messages and print them in a loop 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. 
logo

Java Tutorial

Java Mail API

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 Java mail 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. 

  • 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. 
    • SMTP– Simple 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 mail boxes, which is one mail box for one user.
    • IMAP– Internet Message Access Protocol is also used to receive e-mails. It supports multiple mail boxes for 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. Third layer contains server and protocol implementers. And, the bottom layer is the third party service providers. 

java mail api

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. 

  • Download JavaMail API 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 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. 

  • Setup ‘From’ and ‘To’ address along with the user id and password. 
  • Setup SMTP host 
  • Setup properties values 
  • Create session object 
  • Form the message details 
  • 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 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 session object 
  • Create POP3 store object and connect 
  • Create folder object and open it 
  • Retrieve email messages and print them in a loop 
  • 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. 

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

protective orders in virginia

Keep sharing blogs like this one; they are quite good. You have given everyone in this blog access to a wealth of information.

Johnfrance

Thank you for your valuable information.

sam

Thank you for this wonderful article!

Belay Abera

This article was really helpful to me, thank you!

dfsdf

super article!