0

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

Awordes
  • 3
  • 2

1 Answers1

0

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.

Jalal Sajadi
  • 412
  • 6
  • 12
  • Thank you. How to get the `message` specified in your code? – Awordes Sep 08 '18 at 14:21
  • This is a different question! In this thread you can find yout answer. https://stackoverflow.com/questions/61176/getting-mail-from-gmail-into-java-application-using-imap – Jalal Sajadi Sep 08 '18 at 19:08