Gmail API Error from Code Sample - a bytes-like object is required, not 'str' Gmail API Error from Code Sample - a bytes-like object is required, not 'str' python python

Gmail API Error from Code Sample - a bytes-like object is required, not 'str'


Found a solution, replace this line:

return {'raw': base64.urlsafe_b64encode(message.as_string())}

with:

return {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}

Notice added .encode() and .decode() method calls.

First, str object is encoded to bytes object - base64.urlsafe_b64encode requires it in Python 3 (compared to str object in Python 2).

Then, the base64 encoded bytes object must be decoded back to str. This is needed as googleapiclient library will attempt to json serialize it later in code and that is not possible for bytes objects.