Receiving email with attachment using JavaMail API

As we get the email, we can get the connection likewise by utilizing Multipart and BodyPart classes.

For better comprehension of this illustration, take in the progressions of sending email utilizing JavaMail API first.

For getting or sending the email utilizing JavaMail API, you have to stack the two container records:

  • mail.jar
  • activation.jar

download these jar files go to the Oracle site to download the latest version.

Sample of getting email with connection utilizing JavaMail API

import java.util.*;  
import javax.mail.*;  
import javax.mail.internet.*;  
import javax.activation.*;  
class ReadAttachment{  
  public static void main(String [] args)throws Exception{  
   String host="";  
   final String user="";  
   final String password="*******";//change as needs be   
   Properties properties = System.getProperties();  
   properties.setProperty("",host );  
   properties.put("mail.smtp.auth", "true");  
   Session session = Session.getDefaultInstance(properties,  
    new javax.mail.Authenticator() {  
    protected PasswordAuthentication getPasswordAuthentication() {  
     return new PasswordAuthentication(user,password);  
     Store store = session.getStore("pop3");  
     Folder folder = store.getFolder("inbox");;  
     Message[] message = folder.getMessages();  
  for (int a = 0; a < message.length; a++) {  
    System.out.println("-------------" + (a + 1) + "-----------");  
    Multipart multipart = (Multipart) message[a].getContent();  
    for (int i = 0; i < multipart.getCount(); i++) {  
     BodyPart bodyPart = multipart.getBodyPart(i);  
     InputStream stream = bodyPart.getInputStream();  
     BufferedReader br = new BufferedReader(new InputStreamReader(stream));  
      while (br.ready()) {  

Load the jar file c:\> set classpath=mail.jar;activation.jar;.;
compile the source file c:\> javac
run by c:\> java ReadAttachment