Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

Receiving attachment


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. class ReadAttachment{
  7.   public static void main(String [] args)throws Exception{
  8.    String host=“mail.Kreationnext.com”;
  9.    final String user=“sonoojaiswal@Kreationnext.com”;
  10.    final String password=“xxxxx”;//change accordingly
  11.    Properties properties = System.getProperties();
  12.    properties.setProperty(“mail.smtp.host”,host );
  13.    properties.put(“mail.smtp.auth”“true”);
  14.    Session session = Session.getDefaultInstance(properties,
  15.     new javax.mail.Authenticator() {
  16.     protected PasswordAuthentication getPasswordAuthentication() {
  17.      return new PasswordAuthentication(user,password);
  18.     }
  19.    });
  20.      Store store = session.getStore(“pop3”);
  21.      store.connect(host,user,password);
  22.      Folder folder = store.getFolder(“inbox”);
  23.      folder.open(Folder.READ_WRITE);
  24.      Message[] message = folder.getMessages();
  25.   for (int a = 0; a < message.length; a++) {
  26.     System.out.println(“————-“ + (a + 1) + “———–“);
  27.     System.out.println(message[a].getSentDate());
  28.     Multipart multipart = (Multipart) message[a].getContent();
  29.     for (int i = 0; i < multipart.getCount(); i++) {
  30.      BodyPart bodyPart = multipart.getBodyPart(i);
  31.      InputStream stream = bodyPart.getInputStream();
  32.      BufferedReader br = new BufferedReader(new InputStreamReader(stream));
  33.       while (br.ready()) {
  34.        System.out.println(br.readLine());
  35.       }
  36.      System.out.println();
  37.     }
  38.    System.out.println();
  39.   }
  40.   folder.close(true);
  41.   store.close();
  42.   }
  43. }
download this example to receive email with attachment
Load the jar file c:\> set classpath=mail.jar;activation.jar;.;
compile the source file c:\> javac ReadAttachment.java
run by c:\> java ReadAttachment

Comments

comments