【发布时间】:2014-09-03 17:00:21
【问题描述】:
使用非 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
【问题讨论】:
-
您遇到什么样的错误?包括回溯。
-
你还应该展示一个前置信息的例子。
-
你用的是什么模块;也就是
service的类型是什么? -
+和/是 Base-64 中的第 63 个和第 64 个字符(以及 52 个字母和 10 个数字)。填充是指在 Base-64 字符串的末尾是否存在=符号(需要 0、1 或 2)。有些系统对添加正确的填充不小心。 -
感谢 cmets:@msw 和 Serge 我已添加回溯。 msw 不完全确定这是否是您想要看到的(请参阅我的更新中的“服务”)。乔纳森 - 感谢您的信息,看起来所有消息都以“=”结尾,但可能还不够......