简体   繁体   中英

Extract inline email attachment with Java

I am using following Java code to try extract email attachments:

private static List<File> extractAttachment(Message message) {
    List<File> attachments = new ArrayList<File>();
    try {
        Multipart multipart = (Multipart) message.getContent();

        for (int i = 0; i < multipart.getCount(); i++) {
        BodyPart bodyPart = multipart.getBodyPart(i);
        System.out.println("bodyPart.getDisposition(): " + bodyPart.getDisposition());
        if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
            continue; // dealing with attachments only
        }
        InputStream is = bodyPart.getInputStream();
        String filePath = "/tmp/" + bodyPart.getFileName();
        System.out.println("Saving: " + filePath);
        File f = new File(filePath);
        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);
        }
    } catch (IOException | MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return attachments;
 }

However, I always get bodyPart.getDisposition(): null . Any clue how should I extract inline attachments?

Thanks

PS: I am using Apple Mail client on my Mac for sending test emails with attachment. Email client however should not be of concern.

I got it, indeed I had to some "recursion" and check for nested content and check for Part.INLINE.equalsIgnoreCase(bodyPart.getDisposition() .

Below is the code, think will be useful to someone:

private static List<File> extractAttachment(Multipart multipart) {
    List<File> attachments = new ArrayList<File>();
    try {

        for (int i = 0; i < multipart.getCount(); i++) {
        BodyPart bodyPart = multipart.getBodyPart(i);

        if (bodyPart.getContent() instanceof Multipart) {
            // part-within-a-part, do some recursion...
            extractAttachment((Multipart) bodyPart.getContent());
        }

        System.out.println("bodyPart.getDisposition(): " + bodyPart.getDisposition());
        if (!Part.INLINE.equalsIgnoreCase(bodyPart.getDisposition())) {
            continue; // dealing with attachments only
        }

        InputStream is = bodyPart.getInputStream();
        String filePath = "/tmp/" + bodyPart.getFileName();
        System.out.println("Saving: " + filePath);
        File f = new File(filePath);
        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);
        }
    } catch (IOException | MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return attachments;
    }

I had a similar issue when messages were sent from a mac with no body content but attachments the attachments were not showing up when iterating over the the initial message content and had to be found recursively as well.

I posted what worked for me below.

private Map<String, String> extractAttachments(Multipart multiPart, Map<String, String> attachmentAndName) {
    try {
        for (int i = 0; i < multiPart.getCount(); i++) {
            BodyPart part = multiPart.getBodyPart(i);
            if (part.getContent() instanceof Multipart) {
                attachmentAndName = extractAttachments((Multipart) part.getContent(), attachmentAndName);
            } else if (part instanceof MimeBodyPart) {
                MimeBodyPart mimeBodyPart = (MimeBodyPart) part;
                String fileName = createUniqueFileName(mimeBodyPart.getFileName());
                if (Part.ATTACHMENT.equalsIgnoreCase(mimeBodyPart.getDisposition())) {
                    String attachmentAsString = IOUtils.toString(mimeBodyPart.getInputStream(), StandardCharsets.UTF_8);
                    attachmentAndName.put(fileName, attachmentAsString);
                    if (SAVE_ATTACHMENTS_LOCALLY) {
                        saveFile(mimeBodyPart, fileName);
                    }
                }
            }
        }
    } catch (IOException | MessagingException e) {
        logger.error("Failed to process attachment. Continuing to process other message parts in search of attachments...");
    }
    return attachmentAndName;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM