当前位置:  开发笔记 > 编程语言 > 正文

使用Java Mail下载附件

如何解决《使用JavaMail下载附件》经验,为你挑选了3个好方法。

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

Message[] temp;

如何获取每条消息的附件列表

List attachments;

注意:请不要使用第三方库,只需JavaMail.



1> David Rabino..:

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

List attachments = new ArrayList();
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);
    }
}


StringUtils.isBotnk()不会比使用更自然!StringUtils.isNotBlank?
但是等一下,我们不应该在保存文件之前检查是否(bodyPart.getDisposition()== Part.ATTACHMENT){},这样它就不会保存电子邮件的正文?

2> mefi..:

问题很老,但也许会对某人有所帮助.我想扩展David Rabinowitz的答案.

if(!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))

不应该按照您的预期返回所有内容,因为您可以拥有邮件,其中混合部分没有定义的处置.

   ----boundary_328630_1e15ac03-e817-4763-af99-d4b23cfdb600
Content-Type: application/octet-stream;
    name="00000000009661222736_236225959_20130731-7.txt"
Content-Transfer-Encoding: base64

所以在这种情况下,您还可以检查文件名.像这样:

if (!Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()) && StringUtils.isBlank(part.getFileName())) {...}

编辑

使用上面描述的条件有完整的工作代码.因为每个部分都可以封装另一个部分并且附件应该嵌套,所以递归用于遍历所有部分

public List getAttachments(Message message) throws Exception {
    Object content = message.getContent();
    if (content instanceof String)
        return null;        

    if (content instanceof Multipart) {
        Multipart multipart = (Multipart) content;
        List result = new ArrayList();

        for (int i = 0; i < multipart.getCount(); i++) {
            result.addAll(getAttachments(multipart.getBodyPart(i)));
        }
        return result;

    }
    return null;
}

private List getAttachments(BodyPart part) throws Exception {
    List result = new ArrayList();
    Object content = part.getContent();
    if (content instanceof InputStream || content instanceof String) {
        if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()) || StringUtils.isNotBlank(part.getFileName())) {
            result.add(part.getInputStream());
            return result;
        } else {
            return new ArrayList();
        }
    }

    if (content instanceof Multipart) {
            Multipart multipart = (Multipart) content;
            for (int i = 0; i < multipart.getCount(); i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                result.addAll(getAttachments(bodyPart));
            }
    }
    return result;
}



3> kommradHomer..:

保存附件文件的代码可节省一些时间:

与javax邮件版本1.4及之后,你可以说

// SECURITY LEAK - do not do this! Do not trust the 'getFileName' input. Imagine it is: "../etc/passwd", for example.
// bodyPart.saveFile("/tmp/" + bodyPart.getFileName());

代替

    InputStream is = bodyPart.getInputStream();
    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();


[显然](http://docs.oracle.com/javaee/6/api/javax/mail/internet/MimeBodyPart.html#saveFile(java.lang.String))`bodyPart`应首先转换为`MimeBodyPart` ,如:`((MimeBodyPart)bodyPart).saveFile("/ tmp /"+ bodyPart.getFileName());`
推荐阅读
LEEstarmmmmm
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有