Search code examples
springattachmentincoming-mail

Spring Framework, get incoming emails with attachments using IMAP


Using this link, I could not figure out how to get incoming emails with attachments. For example, the mail [email protected] receives a letter to which the baz.csv file is attached. How to read the contents of a file?
Thank you.


Solution

  • Using java mail platform, you can get attachments of an email:

    Multipart multipart = (Multipart) message.getContent();
    List<byte[]> attachments = new ArrayList<>();
    for (int i = 0; i < multipart.getCount(); i++) {
        BodyPart bodyPart = multipart.getBodyPart(i);
        if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && bodyPart.getFileName()!=null) {
            InputStream is = bodyPart.getInputStream();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            byte[] buf = new byte[4096];
            int bytesRead;
            while ((bytesRead = is.read(buf)) != -1) {
                os.write(buf, 0, bytesRead);
            }
            os.close();
            attachments.add(os.toByteArray());
        }
    }
    

    message is an object of type javax.mail.Message.

    Now, you have a list of byte[] that each one is one of your mail attachment. You can convert byte[] to File easily.