Search code examples
javagmailjakarta-mailemail-attachments

Is there any solution to download email attachment by passing particular email Message ID in Java Using POP?


Currently working on wso2 esb with JavaMail API. what i want to do here is that download unreaded email(Gmail) attachment to some local folder. In ESB end, reading unreaded email and fetching unreaded email's message id task is over and also passing that message id from esb to java also done.From java end, need to download email attachment to that particular message id which is coming from esb end. I don't know how to download email attachment for that particular message id in java.

Could you please help me out to find solution? Thanks in Advance,

Following code, download all email attachment to some local folder.need to download attachment only for that particular message id

public void downloadEmailAttachments(String host, String port,
            String userName, String password) {

     Properties properties = new Properties();


        properties.put("mail.pop3.host", host);
        properties.put("mail.pop3.port", port);


        properties.setProperty("mail.pop3.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        properties.setProperty("mail.pop3.socketFactory.fallback", "false");
        properties.setProperty("mail.pop3.socketFactory.port",
                String.valueOf(port));
        Session session = Session.getDefaultInstance(properties);
        try {
        Store store = session.getStore("pop3");
        store.connect(userName, password);  
        Folder folderInbox = store.getFolder("INBOX");
        folderInbox.open(Folder.READ_ONLY);
        Message[] arrayMessages = folderInbox.getMessages();


        for (int i = 0; i < arrayMessages.length; i++) {
            Message message = arrayMessages[i];
            Address[] fromAddress = message.getFrom();
            String from = fromAddress[0].toString();
            String subject = message.getSubject();
            String sentDate = message.getSentDate().toString();

            String contentType = message.getContentType();


            String messageContent = "";

            // store attachment file name, separated by comma
            String attachFiles = "";

            if (contentType.contains("multipart")) {

                Multipart multiPart = (Multipart) message.getContent();
                int numberOfParts = multiPart.getCount();
                for (int partCount = 0; partCount < numberOfParts; partCount++) {
                    MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                    if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                        // this part is attachment
                        String fileName = part.getFileName();
                        attachFiles += fileName + ", ";
                        part.saveFile(saveDirectory + File.separator + fileName);
                    } else {
                        // this part may be the message content
                        messageContent = part.getContent().toString();
                    }
                }

                if (attachFiles.length() > 1) {
                    attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
                }
            } else if (contentType.contains("text/plain")
                    || contentType.contains("text/html")) {
                Object content = message.getContent();
                if (content != null) {
                    messageContent = content.toString();
                }
            }

            // print out details of each message
            System.out.println("Message #" + (i + 1) + ":");
            System.out.println("\t From: " + from);
            System.out.println("\t Subject: " + subject);
            System.out.println("\t Sent Date: " + sentDate);
            System.out.println("\t Message: " + messageContent);
            System.out.println("\t Attachments: " + attachFiles);
        }

        // disconnect
        folderInbox.close(false);
        store.close();
    } catch (NoSuchProviderException ex) {
        System.out.println("No provider for pop3.");
        ex.printStackTrace();
    } catch (MessagingException ex) {
        System.out.println("Could not connect to the message store");
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

 }

Solution

  • There's no efficient way to do this using POP3. POP3 will require the client to read at least all of the headers of each message in order to find the message that matches the messageId. IMAP can do this much more efficiently.

    Using either protocol, you can use the Folder.search method with a MessageIDTerm to find the right message.

    Note also that you'll want to fix these common JavaMail mistakes in your code.