'How to recover a .jpg image from a encoded GMail attachment in Python

I'm using the GMail API in Python. I am succesfully downloading the attachment of an email using

attachment = service.users().messages().attachments().get(userId='me', messageId = msg_id, id=attachment_id).execute()

From this I can recover the data and decode it using

data = attachement['data']
decoded_data = base64.urlsafe_b64decode(data.encode('utf-8'))

However, I do not understand how to recover the .jpg from this string.



Solution 1:[1]

The answer is very straightforward. First two functions from 2 different libraries must be imported:

from io import BytesIO
from PIL import Image

Then the image can be saved using these two functions:

im = Image.open(BytesIO(decoded_data))
im.save('attachement', 'JPEG')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 wvdk