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.
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.
Now the environment setup is complete and we will jump into the coding part.
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.
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
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.
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.
Keep sharing blogs like this one; they are quite good. You have given everyone in this blog access to a wealth of information.
Thank you for your valuable information.
Thank you for this wonderful article!
This article was really helpful to me, thank you!
super article!
Leave a Reply
Your email address will not be published. Required fields are marked *