Receiving email with attachment in Java

Example of receiving attachment with email in Java provides examples of sending, receiving, forwarding and deleting emails, Learn how to receive attachment in java

Receiving email with attachment in Java

Receiving email with attachment in Java

As we receive the email, we can receive the attachment also by using Multipart and BodyPart classes found in JavaMail API.

For better understanding of this example, learn the steps of sending email using JavaMail API first.

For receiving or sending the email using JavaMail API, you need to load the two jar files:

  • mail.jar
  • activation.jar

Example of receiving email with attachment in Java

  1. import java.util.*;  
  2. import javax.mail.*;  
  3. import javax.mail.internet.*;  
  4. import javax.activation.*;  
  5. import java.io.*;  
  6.   
  7. class ReadAttachment{  
  8.   public static void main(String [] args)throws Exception{  
  9.      
  10.    String host="mail.samtpoint.com";  
  11.    final String user="sam@samtpoint.com";  
  12.    final String password="xxxxx";//change accordingly  
  13.   
  14.    Properties properties = System.getProperties();  
  15.    properties.setProperty("mail.smtp.host",host );  
  16.    properties.put("mail.smtp.auth""true");  
  17.   
  18.    Session session = Session.getDefaultInstance(properties,  
  19.     new javax.mail.Authenticator() {  
  20.     protected PasswordAuthentication getPasswordAuthentication() {  
  21.      return new PasswordAuthentication(user,password);  
  22.     }  
  23.    });  
  24.         
  25.      Store store = session.getStore("pop3");  
  26.      store.connect(host,user,password);  
  27.   
  28.      Folder folder = store.getFolder("inbox");  
  29.      folder.open(Folder.READ_WRITE);  
  30.   
  31.      Message[] message = folder.getMessages();  
  32.   
  33.   
  34.   for (int a = 0; a < message.length; a++) {  
  35.     System.out.println("-------------" + (a + 1) + "-----------");  
  36.     System.out.println(message[a].getSentDate());  
  37.   
  38.     Multipart multipart = (Multipart) message[a].getContent();  
  39.    
  40.     for (int i = 0; i < multipart.getCount(); i++) {  
  41.      BodyPart bodyPart = multipart.getBodyPart(i);  
  42.      InputStream stream = bodyPart.getInputStream();  
  43.      BufferedReader br = new BufferedReader(new InputStreamReader(stream));  
  44.   
  45.       while (br.ready()) {  
  46.        System.out.println(br.readLine());  
  47.       }  
  48.      System.out.println();  
  49.     }  
  50.    System.out.println();  
  51.   }  
  52.   
  53.   folder.close(true);  
  54.   store.close();  
  55.   }  
Load the jar file c:\> set classpath=mail.jar;activation.jar;.;
compile the source file c:\> javac ReadAttachment.java
run by c:\> java ReadAttachment