Spring Framework,使用IMAP获取带附件的传入电子邮件

问题描述 投票:0回答:1

使用this链接,我无法弄清楚如何收到附件的传入电子邮件。例如,邮件[email protected]会收到一封附有baz.csv文件的信件。如何读取文件的内容? 谢谢。

spring attachment incoming-mail
1个回答
0
投票

使用java邮件平台,您可以获取电子邮件的附件:

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());
    }
}

messagejavax.mail.Message类型的对象。

现在,您有一个byte []列表,每个列表都是您的邮件附件之一。您可以轻松地将byte []转换为File。

© www.soinside.com 2019 - 2024. All rights reserved.