B64解码的问题

sac*_*shu 2 python gmail-api

使用非mime message.get方法,我将取出正文/数据并尝试对其进行解码,以便简单地用英语显示消息.我遇到的问题是一些消息解码很好,然后突然我得到不正确的填充问题.我试过替换+和/无济于事.

为什么会发生这种情况,我该如何解决?

这是我的messages.get方法:

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
Run Code Online (Sandbox Code Playgroud)

更新

服务

gmail_service = build('gmail', 'v1', http=http)
Run Code Online (Sandbox Code Playgroud)

回溯错误

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
Run Code Online (Sandbox Code Playgroud)

使用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
Run Code Online (Sandbox Code Playgroud)

Jay*_*Lee 11

你需要使用:

message_decoded = base64.urlsafe_b64decode(message_raw)
Run Code Online (Sandbox Code Playgroud)

因为原始消息是URLSafe base64编码.

  • 我想我想出来了 - 我需要在将message_raw传递给urlsafe方法之前将其转换为str. (5认同)
  • 当我使用它时,这是以下错误(原始帖子中的回溯):TypeError:字符映射必须返回整数,无或unicode (2认同)