B64解码问题

2 投票
1 回答
2755 浏览
提问于 2025-04-18 13:09

我在使用非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

1 个回答

11

你需要使用:

message_decoded = base64.urlsafe_b64decode(message_raw)

因为原始信息是用URL安全的base64编码的。

撰写回答