We already discussed the basics of Java Mail API.Also we discussed the way by which Java mail API is sending mails with attachment and without attachment. In this chapter we are discussing how POP is using in Java Mail API to receive emails.We are discussing it with an example which reads mails from inbox of Gmail account.
Post Office Protocol(POP) – An overview
POP is a protocol using by email clients to retrieve emails from mail servers over a TCP/IP network.POP version 3 (POP3) is the current POP standard. Most email providers like Gmail ,Yahoo are supporting POP. Both POP and IMAP(Internet Message Access Protocol) are widely used by email clients to retrieve emails from mail servers.
POP vs IMAP
By using POP an email will be downloaded fully.So those mails will be available in offline also.IMAP allows syncing between mail server and clients. Once we read a mail , it will be marked as read in the web.If we open our mail account from any anther client , then the previously read mail will not be displayed as unread.POP is useful when two way synchronization is not needed.
Reading email in Java using POP-Example
Put the following class in a dynamic web project.(If we need to access mails from J2SE application , then we can download Java Mail API from here.Extract the zip file and include the jar files in the project path).
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
public class ReceiveMail {
Properties properties = null;
private Session session = null;
private Store store = null;
private Folder inbox = null;
private String userName = "";// provide user name
private String password = "";// provide password
public ReceiveMail() {
}
public void receiveMail() {
properties = new Properties();
properties.setProperty("mail.pop3.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.pop3.socketFactory.fallback", "false");
properties.setProperty("mail.pop3.host", "pop.gmail.com");
properties.setProperty("mail.pop3.port", "995");
properties.setProperty("mail.pop3.socketFactory.port", "995");
session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
try {
store = session.getStore("pop3");
store.connect();
inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for (int i = 1; i < messages.length; i++) { Message message = messages[i]; Address[] from = message.getFrom(); System.out.println("-------------------------------"); System.out.println("Date : " + message.getSentDate()); System.out.println("From : " + from[0]); System.out.println("Subject: " + message.getSubject()); System.out.println("Content :"); processMessageBody(message); System.out.println("--------------------------------"); } } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } /** * Parses the message content * * @param message */ public void processMessageBody(Message message) { try { Object content = message.getContent(); // check for string // then check for multipart if (content instanceof String) { System.out.println(content); } else if (content instanceof Multipart) { Multipart multiPart = (Multipart) content; procesMultiPart(multiPart); } else if (content instanceof InputStream) { InputStream inStream = (InputStream) content; int ch; while ((ch = inStream.read()) != -1) { System.out.write(ch); } } } catch (IOException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } /** * recursively processes multipart messages * * @param content */ public void procesMultiPart(Multipart content) { try { int multiPartCount = content.getCount(); for (int i = 0; i < multiPartCount; i++) { BodyPart bodyPart = content.getBodyPart(i); Object o; o = bodyPart.getContent(); if (o instanceof String) { System.out.println(o); } else if (o instanceof Multipart) { procesMultiPart((Multipart) o); } } } catch (IOException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } public static void main(String[] args) { ReceiveMail sample = new ReceiveMail(); sample.receiveMail(); } }
This application establishes a connection with Gmail server using POP3. Then it is accessing the inbox and reading emails one by one.If the message is a string message then it is displayed directly.If the message is a Multipart instance then iteration over the message body takes place .
Output
Provide values for the variables userName and password.Then compile and run the application.The entire mails in the Gmail inbox will be displayed. It may take much time to fetch all the mails , if inbox contains more number of mails.
See also
SMTP
Sending email using Java Mail API
Sending email with attachment using Java Mail API
IMAP