Reading email attachments in java

We are explaining here an example of receiving or fetching email with attachment using JavaMail API. The Store, Folder, Multipart and BodyPart classes are used to receive an email with attachment using JavaMail API.

Steps of reading email attachments in java using JavaMail API:

  1. Get the Session object.
  2. Create the POP3 store object and connect to the pop store.
  3. Create the folder object and open it in your mailbox.
  4. Retrieve the messages from the folder object.
  5. Retrieve the Multipart object from message object.
  6. Retrieve the BodyPart object from the Multipart object.
  7. Close the folder and store objects.

Example:

ReceiveEmailWithAttachment.java

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties; 
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
 
/**
 * This class is used to receive email with attachment.
 * @author w3spoint
 */
public class ReceiveEmailWithAttachment { 
 public static void receiveEmail(String pop3Host,
    String mailStoreType, String userName, String password){
    //Set properties
    Properties props = new Properties();
    props.put("mail.store.protocol", "pop3");
    props.put("mail.pop3.host", pop3Host);
    props.put("mail.pop3.port", "995");
    props.put("mail.pop3.starttls.enable", "true");
 
    // Get the Session object.
    Session session = Session.getInstance(props);
 
    try {
        //Create the POP3 store object and connect to the pop store.
	Store store = session.getStore("pop3s");
	store.connect(pop3Host, userName, password);
 
	//Create the folder object and open it in your mailbox.
	Folder emailFolder = store.getFolder("INBOX");
	emailFolder.open(Folder.READ_ONLY);
 
	//Retrieve the messages from the folder object.
	Message[] messages = emailFolder.getMessages();
	System.out.println("Total Message" + messages.length);
 
	//Iterate the messages
	for (int i = 0; i < messages.length; i++) {
	   Message message = messages[i];
	   Address[] toAddress = 
             message.getRecipients(Message.RecipientType.TO);
	     System.out.println("---------------------------------");  
	     System.out.println("Details of Email Message " 
                                                   + (i + 1) + " :");  
	     System.out.println("Subject: " + message.getSubject());  
	     System.out.println("From: " + message.getFrom()[0]);  
 
	     //Iterate recipients 
	     System.out.println("To: "); 
	     for(int j = 0; j < toAddress.length; j++){
	       System.out.println(toAddress[j].toString());
	     }
 
	     //Iterate multiparts
	     Multipart multipart = (Multipart) message.getContent();
	     for(int k = 0; k < multipart.getCount(); k++){
	       BodyPart bodyPart = multipart.getBodyPart(k);  
	       InputStream stream = 
                             (InputStream) bodyPart.getInputStream();  
	       BufferedReader bufferedReader = 
	    	   new BufferedReader(new InputStreamReader(stream));  
 
	        while (bufferedReader.ready()) {  
	    	       System.out.println(bufferedReader.readLine());  
	    	}  
	    	   System.out.println();  
	      }  
	   }
 
	   //close the folder and store objects
	   emailFolder.close(false);
	   store.close();
	} catch (NoSuchProviderException e) {
		e.printStackTrace();
	} catch (MessagingException e){
		e.printStackTrace();
	} catch (Exception e) {
	       e.printStackTrace();
	}
 
    }
 
 public static void main(String[] args) {
  String pop3Host = "pop.gmail.com";//change accordingly
  String mailStoreType = "pop3";	
  final String userName = "w3spoint";//change accordingly
  final String password = "****";//change accordingly
 
  //call receiveEmail
  receiveEmail(pop3Host, mailStoreType, userName, password);
 }
}

Output:

Details of Email Message 1 :
Subject: Give your profile a makeover.
From: Twitter <info@twitter.com>
To: 
w3spoint <w3spoint@gmail.com>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" 
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; 
charset=utf-8" />
<meta name="viewport" content="width=device-width,
 minimum-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<meta name="apple-mobile-web-app-capable" content="yes" />
</head>
<body bgcolor="#e9edef" style="margin:0;padding:0;
-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;">
<table cellpadding="0" cellspacing="0" border="0"
 width="100%" bgcolor="#e9edef" style="background-color:
#e9edef;padding:0;margin:0;line-height:1px;font-size:1px;"
 class="body_wrapper">
<style type="text/css">
 
 
@media only screen and (max-device-width: 480px) {
 
table[class="collapse"]{
width:100% !important;
}
 
 
 
img[class="hero"]{
width:100% !important;
}
 
span[class="headline_1"] {
font-size:28px !important;
 
}
 
td[class="body_text"] {
font-size:14px !important;
line-height:22px !important;
width:238px !important;
 
}
 
span[class="address"] a {
 
line-height:16px !important;
}
 
td[class="margins"]{
width:42px !important;
}
 
td[class="v_space"]{
height:16px !important;
}
 
td[class="logo_space"]{
height:12px !important;
}
 
span[class="address"]{
display:block !important;
width:240px !important;
}
 
}
</style>
<tbody>
<tr>
<td align="center" style="padding:0;margin:0;
line-height:1px;font-size:1px;">
...

Download this example.
 
Next Topic: Replying emails with example.
Previous Topic: Receiving emails with example.

 

Content Protection by DMCA.com
Please Share