使用Java邮件下载附件

问题描述 投票:94回答:5

现在,I`ve下载的所有邮件,并将它们存储到

Message[] temp;

如何获取附件列表中为每个消息的

List<File> attachments;

注:没有第三方库,请,只是JavaMail的。

java attachment javamail
5个回答
105
投票

如果没有异常处理,但这里有云:

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

32
投票

问题是很老,但也许它会帮助别人。我想扩大大卫Rabinowitz`s答案。

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<InputStream> getAttachments(Message message) throws Exception {
    Object content = message.getContent();
    if (content instanceof String)
        return null;        

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

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

    }
    return null;
}

private List<InputStream> getAttachments(BodyPart part) throws Exception {
    List<InputStream> result = new ArrayList<InputStream>();
    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<InputStream>();
        }
    }

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

9
投票

对于您保存附件文件中的代码部分的节省时间:

与使用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();

3
投票

你可以简单地使用Apache共享邮件API MimeMessageParser - getAttachmentList()一起共享IO和共享郎。

MimeMessageParser parser = ....
parser.parse();
for(DataSource dataSource : parser.getAttachmentList()) {

    if (StringUtils.isNotBlank(dataSource.getName())) {}

        //use apache commons IOUtils to save attachments
        IOUtils.copy(dataSource.getInputStream(), ..dataSource.getName()...)
    } else {
        //handle how you would want attachments without file names
        //ex. mails within emails have no file name
    }
}

0
投票

这里是我的mefi's solution的再现。

private static void attachments(
    final BodyPart body, final BiConsumer<String, InputStream> consumer)
    throws MessagingException, IOException {
    final Multipart content;
    try {
        content = (Multipart) body.getContent();
        for (int i = 0; i < content.getCount(); i++) {
            attachments(content.getBodyPart(i), consumer);
        }
        return;
    } catch (final ClassCastException cce) {
    }
    if (!Part.ATTACHMENT.equalsIgnoreCase(body.getDisposition())) {
        return;
    }
    final String name = body.getFileName();
    if (name == null || name.trim().isEmpty()) {
        return;
    }
    try (final InputStream stream = body.getInputStream()) {
        consumer.accept(name, stream);
    }
}

public static void attachments(
    final Message message, final BiConsumer<String, InputStream> consumer)
    throws IOException, MessagingException {
    final Multipart content;
    try {
        content = (Multipart) message.getContent();
    } catch (final ClassCastException cce) {
        return;
    }
    for (int i = 0; i < content.getCount(); i++) {
        attachments(content.getBodyPart(i), consumer);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.