【问题标题】:Spring Framework, get incoming emails with attachments using IMAPSpring Framework,使用 IMAP 获取带有附件的传入电子邮件
【发布时间】:2019-02-13 11:53:38
【问题描述】:

使用this 链接,我无法弄清楚如何获取带有附件的传入电子邮件。例如,邮件 foo@bar.com 收到一封附有 baz.csv 文件的信件。如何读取文件的内容?
谢谢。

【问题讨论】:

    标签: spring attachment incoming-mail


    【解决方案1】:

    使用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。

    【讨论】:

    猜你喜欢
    • 2013-04-11
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2022-08-03
    • 1970-01-01
    • 2016-05-07
    • 1970-01-01
    • 2013-04-30
    相关资源
    最近更新 更多