Search code examples
javaemailjakarta-mail

Issue reading email body when email has attachments?


I found a nice code to read email from my inbox email server, the code works just fine, but have a couple issues:

  1. I need to capture the message body of each email, but when the email has some attachment, i receive a string like this javax.mail.internet.MimeMultipart@100363, or com.sun.mail.util.BASE64DecoderStream@14e8cee, instead of the body message. If the email is just plain text and have no attachments, it works just fine. seems i am not the only one with this problem, i have been reading over the web but can't find a solution.

  2. I would like to ignore attachments when its size exceed 4 MB.

Below is the class, i will appreciate any comments. it's important to say that i am a novice programmer in java. thanks in advance !

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; 
    private String password;
    String downloadDirectory = "D:/Attachment/";

    public ReadMailSample() {
        userName = "[email protected]";// provide user name
        password = "mypassword";// provide password
    }

    public void readMails() {
        properties = new Properties();
        properties.setProperty("mail.host", "imap.secureserver.net");
        properties.setProperty("mail.port", "110");
        properties.setProperty("mail.transport.protocol", "imap");
        session = Session.getInstance(properties,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(userName, password);
                    }
                });
        try {
            store = session.getStore("imap");
            store.connect();
            inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_WRITE);
            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("--> ** E-mail No. "+ i + " **");
                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) {
                System.out.println(content);
                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("Text = " + o);
                    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();
    }
}

Solution

    1. From the JavaMail FAQ:

    2. Define "ignore". Did you see the getSize method?