wvdk
wvdk

Reputation: 99

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.

Upvotes: 0

Views: 131

Answers (1)

wvdk
wvdk

Reputation: 99

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')

Upvotes: 1

Related Questions