Reading email with Attachment in Java

We have discussed the fundamentals of Java Mail API. We discussed the way with which java mail API uses SMTP to send emails with attachment and without attachment.We also discussed the use of POP3 and IMAP in Java Mail API.In the just previous chapter we discussed the way with Java Mail API deletes email.In this post , we are discussing  how Java Mail API reads an email with attachment.

Reading email with Attachment in Java

We are accessing Gmail server in our application. We are using IMAP as email retrieving  protocol.Our application reads all unread mails from inbox and displays the content in console.If the mail contains attachments , then those attachments will be saved to the ‘downloadDirectory’ folder mentioned in the code.

The following class  needs to put in a dynamic web project because Java Mail API is there in J2EE.(If we need to use Java mail API features to J2SE application , then  we can download the Java Mail API .It is available here for download.Extract the file and put the jar files in the application path).

ReadMailSample.java

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Flags.Flag;
import javax.mail.search.FlagTerm;

public class ReadMailSample {
Properties properties = null;
private Session session = null;
private Store store = null;
private Folder inbox = null;
private String userName = "";// provide user name
private String password = "";// provide password
String downloadDirectory = "C:/tmp/downloads/";

public ReadMailSample() {

}

public void readMails() {
properties = new Properties();
properties.setProperty("mail.host", "imap.gmail.com");
properties.setProperty("mail.port", "995");
properties.setProperty("mail.transport.protocol", "imaps");
session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
try {
store = session.getStore("imaps");
store.connect();
inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.search(new FlagTerm(
new Flags(Flag.SEEN), false));
;
System.out.println("Number of mails = " + messages.length);
for (int i = 0; i < messages.length; i++) { Message message = messages[i]; Address[] from = message.getFrom(); System.out.println("-------------------------------"); System.out.println("Date : " + message.getSentDate()); System.out.println("From : " + from[0]); System.out.println("Subject: " + message.getSubject()); System.out.println("Content :"); processMessageBody(message); System.out.println("--------------------------------"); } inbox.close(true); store.close(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } public void processMessageBody(Message message) { try { Object content = message.getContent(); // check for string // then check for multipart if (content instanceof String) { System.out.println(content); } else if (content instanceof Multipart) { Multipart multiPart = (Multipart) content; procesMultiPart(multiPart); } else if (content instanceof InputStream) { InputStream inStream = (InputStream) content; int ch; while ((ch = inStream.read()) != -1) { System.out.write(ch); } } } catch (IOException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } public void procesMultiPart(Multipart content) { try { for (int i = 0; i < content.getCount(); i++) { BodyPart bodyPart = content.getBodyPart(i); Object o; o = bodyPart.getContent(); if (o instanceof String) { System.out.println("Text = " + o); } else if (null != bodyPart.getDisposition() && bodyPart.getDisposition().equalsIgnoreCase( Part.ATTACHMENT)) { String fileName = bodyPart.getFileName(); System.out.println("fileName = " + fileName); InputStream inStream = bodyPart.getInputStream(); FileOutputStream outStream = new FileOutputStream(new File( downloadDirectory + fileName)); byte[] tempBuffer = new byte[4096];// 4 KB int numRead; while ((numRead = inStream.read(tempBuffer)) != -1) { outStream.write(tempBuffer); } inStream.close(); outStream.close(); } // else? } } catch (IOException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } public static void main(String[] args) { ReadMailSample sample = new ReadMailSample(); sample.readMails(); } }

Output

provide username and password of Gmail account . Then Compile and run the above application.The unread mails will be displayed in the console.If any mail contains attachments , then those attachments will be downloaded to the folder 'downloadDirectory'.

See Related Discussions:

Java Mail API Tutorial

Deleting email in Java Mail API

SMTP

Sending email

Sending email with attachment

POP

Reading email using POp3

IMAP

Reading email  using IMAP

3 thoughts on “Reading email with Attachment in Java

  1. Raghu Reply

    Hi,
    I tried the same code to read the mail content with attachment over IMAP protocol.
    If i understood correctly, the above code is getting the mail into parts when mail has an inline attachment and second part will have the information of attachment. First part contains the mail content. So i am trying to read the mail content first part using getContent(). But it returns null.
    Any idea why is this issue?

    Or else can you provide the working sample code to read the mail content and also the inline attachment over imap.

    • packnik Reply

      Attachements can be put in two ways…by attaching to email and by putting that in mail body.
      Above code will read attachements that are attached with the mail. In order to ready attachements in body you need to put additional conditions as below

      part.getFileName() != null && (part.getDisposition() == null || part.getDisposition().equals(ATTACHMENT));

      This will help to read attachements that are in body.

  2. akash Reply

    Hi,

    1)Null pointer exception will come if there is no new email or unread email,
    2)the code has some issue, it will not download the attachment, it will just read the name of the attachment.

    @Author
    Please post some other solution if you have.

Leave a Reply

Your email address will not be published. Required fields are marked *