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.*;  
import java.io.*;  
  
class ReadAttachment{  
  public static void main(String [] args)throws Exception{  
     
   String host="mail.javatportal.com";  
   final String user="mithilesh@javatportal.com";  
   final String password="*******";//change as needs be   
  
   Properties properties = System.getProperties();  
   properties.setProperty("mail.smtp.host",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");  
     store.connect(host,user,password);  
  
     Folder folder = store.getFolder("inbox");  
     folder.open(Folder.READ_WRITE);  
  
     Message[] message = folder.getMessages();  
  
  
  for (int a = 0; a < message.length; a++) {  
    System.out.println("-------------" + (a + 1) + "-----------");  
    System.out.println(message[a].getSentDate());  
  
    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()) {  
       System.out.println(br.readLine());  
      }  
     System.out.println();  
    }  
   System.out.println();  
  }  
  
  folder.close(true);  
  store.close();  
  }  
}  

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