java - 使用 Java Mail 下载附件

标签 java attachment jakarta-mail

现在我已经下载了所有消息,并将它们存储到

Message[] temp;

如何获取每封邮件的附件列表

List<File> attachments;

注意:没有第三方库,请只使用 JavaMail。

最佳答案

没有异常处理,但这里是:

List<File> attachments = new ArrayList<File>();
for (Message message : temp) {
    Multipart multipart = (Multipart) message.getContent();

    for (int i = 0; i < multipart.getCount(); i++) {
        BodyPart bodyPart = multipart.getBodyPart(i);
        if(!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) &&
               StringUtils.isBlank(bodyPart.getFileName())) {
            continue; // dealing with attachments only
        } 
        InputStream is = bodyPart.getInputStream();
        // -- EDIT -- SECURITY ISSUE --
        // do not do this in production code -- a malicious email can easily contain this filename: "../etc/passwd", or any other path: They can overwrite _ANY_ file on the system that this code has write access to!
//      File f = new File("/tmp/" + bodyPart.getFileName());
        FileOutputStream fos = new FileOutputStream(f);
        byte[] buf = new byte[4096];
        int bytesRead;
        while((bytesRead = is.read(buf))!=-1) {
            fos.write(buf, 0, bytesRead);
        }
        fos.close();
        attachments.add(f);
    }
}

关于java - 使用 Java Mail 下载附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1748183/

相关文章:

java - 两个重载的方法,相同的 Action ,导致重复代码

java - XMLFormatter 中的 getTail() 方法如何工作?

vba - 如何覆盖从磁盘上的 zip 中提取的文件?

vba - 如何从 Outlook 中提取附件、另存为主题行并删除无效字符?

java - 使用 Java Mail API 保存电子邮件(包括图像和 HTML 数据)的最佳方式?

java - 如何使用java-Google Docs Api将文件上传到Google Drive?

java - 使用应用程序 Api key 将注释发布到 Facebook 页面

java - 最终引用对象被修改

java - 在 GWT 中使用 RequestBuilder 处理附件以响应

grails - 创建名称为 'mailSender'的bean时出错