使用非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
更新
服务
gmail_service = build('gmail', 'v1', http=http)
追踪错误
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
使用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
答案 0 :(得分:11)
您需要使用:
message_decoded = base64.urlsafe_b64decode(message_raw)
因为原始邮件是URLSafe base64 encoded。