Search code examples
javagmail-api

Downloading attachments with the Gmail API fails


Using code that is similar to the API reference site I am getting and null exception error at the beginning of the for-loop. I've checked that the message has an attachment, but it appears to inline. For other messages where the attachment is not inline it does work.

What do I have to do to get inline attachments?

public List<Attachment> getAttachments(String messageId) throws IOException
{
    List<Attachment> attachments = new ArrayList<>();
    Message message = SERVICE.users().messages().get(USER, messageId).execute();
    List<MessagePart> parts = message.getPayload().getParts();
    if (parts != null)
    {
    
        for (MessagePart part : parts)
        {
            if (part.getFilename() != null && part.getFilename().length() > 0)
            {
                String attId = part.getBody().getAttachmentId();
                MessagePartBody attachPart = SERVICE.users().messages().attachments().
                        get(USER, messageId, attId).execute();

                byte[] fileByteArray = Base64.decodeBase64(attachPart.getData());
                Attachment attachment = new Attachment(part, attachPart, fileByteArray);
                attachments.add(attachment);
            }
        }
    }
    return attachments;
}

Solution

  • You may elaborate inline attachments via message.getPayload().getBody().

    I suggest you to test it first:

    if (message.getPayload().getBody().size() > 0) {
        // do your work with:
        // message.getPayload().getBody()
    } else {
        // do your work with:
        // message.getPayload().getParts()
    }
    

    For further information, please refer to the official Gmail API documentation:

    And especially to the line:

    "body": users.messages.attachments Resource

    Hope this helps.