Receiving or fetching simple email using JavaMail API

We are explaining here an example of receiving or fetching simple email using JavaMail API. The Store and Folder classes are used to receive an email using JavaMail API.

Steps of receiving or fetching simple email using JavaMail API:

    1. Get a session instance from getDefaultInstance() or getInstance() method of Session class. 2. Create the store object (POP3) and connect to the pop store. 3. Create the folder object by calling getFolder() method on store object and open it in mailbox. 4. Get the messages from the folder object. 5. Close the folder and store objects.

Example:

ReceiveEmail.java

import java.util.*;  
import javax.mail.*;  
 
/**
 * This class is used to receive simple email.
 * @author w3spoint
 */
public class ReceiveEmail { 
public static void receiveEmail(String pop3Host, 
		String storeType, String user, String password){
	Properties props = new Properties();
	props.put("mail.pop3.host", pop3Host);
	props.put("mail.pop3.port", "995");
	props.put("mail.pop3.starttls.enable", "true");
	props.put("mail.store.protocol", "pop3");
 
Session session = Session.getInstance(props);	
try {  
	Store mailStore = session.getStore(storeType);
	mailStore.connect(pop3Host, user, password);
 
	Folder folder = mailStore.getFolder("INBOX");
	folder.open(Folder.READ_ONLY);
 
	Message[] emailMessages = folder.getMessages();
	System.out.println("Total Message - " 
			+ emailMessages.length);
 
   //Iterate the messages
  for (int i = 0; i < emailMessages.length; i++) {
   Message message = emailMessages[i];
   Address[] toAddress = 
   message.getRecipients(Message.RecipientType.TO);
   System.out.println();  
   System.out.println("Email " + (i+1) + "-");  
   System.out.println("Subject - " + message.getSubject());  
   System.out.println("From - " + message.getFrom()[0]); 
 
   System.out.println("To - "); 
   for(int j = 0; j < toAddress.length; j++){
	   System.out.println(toAddress[j].toString());
   }
   System.out.println("Text - " + 
		   message.getContent().toString());  
  }
 
   folder.close(false);
   mailStore.close();
} catch (Exception e) {
    e.printStackTrace();
    System.err.println("Error in receiving email.");
    }        
}
 
public static void main(String[] args) {
 String pop3Host = "pop.gmail.com";
 String mailStoreType = "pop3s";	
 final String userName = "[email protected]";
 final String password = "****";
 
 //call receiveEmail
 receiveEmail(pop3Host, mailStoreType, userName, password);
}
}

Output:

Total Message - 257
 
Email 1-
Subject - Add a profile photo
From - Google+ <noreply-2792efbc@plus.google.com>
To - 
w3spoint99@gmail.com
Text - javax.mail.internet.MimeMultipart@84a74

Download this example.   Next Topic: Receiving emails with attachments with example. Previous Topic: Send email through Gmail server using SSL connection with example.

 

Please follow and like us:
Content Protection by DMCA.com