Sunday, September 15, 2019

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
download these jar files (or) go to the Oracle site to download the latest version.

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.javatpoint.com";  
  11.    final String user="sonoojaiswal@javatpoint.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.   }  
  56. }  

Load the jar filec:\> set classpath=mail.jar;activation.jar;.;
compile the source filec:\> javac ReadAttachment.java
run byc:\> java ReadAttachment

No comments:

Post a Comment

How to DROP SEQUENCE in Oracle?

  Oracle  DROP SEQUENCE   overview The  DROP SEQUENCE  the statement allows you to remove a sequence from the database. Here is the basic sy...