Issues with B64 decoding

gmail-api, python

Solution

You need to use:

message_decoded = base64.urlsafe_b64decode(message_raw)

since the raw message is URLSafe base64 encoded.

Problem

Using the non-mime message.get method, I am pulling out the body/data and trying to decode it in order to simply show the message in english. The problem I am having is that some of the messages decode fine, and then suddenly I get incorrect padding issues. I have tried replacing + and / to no avail. Why would this be happening and how do I fix it? Here's my messages.get method: ``` try: message = service.users().messages().get(userId=user_id, id=msg_id).execute() # Pull Raw Message Body from Response message_raw = message['payload']['parts'][0]['body']['data'] # Decode the raw message message_decoded = base64.b64decode(message_raw) # Print the messages print message_decoded ``` UPDATES Service ``` gmail_service = build('gmail', 'v1', http=http) ``` Traceback Error ``` Traceback (most recent call last): File "gmail.py", line 166, in <module> GetMessage(gmail_service, 'me', message_id) File "gmail.py", line 155, in GetMessage message_decoded = base64.b64decode(message_raw) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/base64.py", line 76, in b64decode raise TypeError(msg) TypeError: Incorrect padding ``` Traceback error when using urlsafe ``` Traceback (most recent call last): File "gmail.py", line 166, in <module> GetMessage(gmail_service, 'me', message_id) File "gmail.py", line 155, in GetMessage message_decoded = base64.urlsafe_b64decode(message_raw) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/base64.py", line 112, in urlsafe_b64decode return b64decode(s, '-_') File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/base64.py", line 71, in b64decode s = _translate(s, {altchars[0]: '+', altchars[1]: '/'}) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/base64.py", line 36, in _translate return s.translate(''.join(translation)) TypeError: character mapping must return integer, None or unicode ```

Original source

Related problems