Python Gmail Api Base64 解码电子邮件正文中的奇怪字符

Pri*_*ign 3 python base64 gmail-api

我正在使用 Gmail API 从我的收件箱中检索电子邮件:

query = 'to:me after:{}'.format(weekStartDate)

unreadEmailsQuery = service.users().messages().list(userId='me', q=query).execute()

# For Each Email
for message in unreadEmailsQuery['messages']:
    result = service.users().messages().get(id=message['id'],userId='me').execute()
  email_content = ''

  if 'data' in result['payload']['body'].keys():
         email_content+= result['payload']['body']['data']
    else:

        for part in result['payload']['parts']:
            email_content = part['body']['data'] + email_content



    test = bytes(str(email_content),encoding='utf-8')
    print(base64.decodebytes(test))
Run Code Online (Sandbox Code Playgroud)

正确打印出简单的纯文本消息:

b'Got another one with me

但是会像这样打印出 html 消息:

b'<body\x03B\x83B\x83B\x83B\x88\x08\x0f\x1bY]\x18H\x1a\x1d\x1d\x1c\x0bY\\]Z]\x8fH\x90\xdb\
Run Code Online (Sandbox Code Playgroud)

我可以看到,直到第一个 > 从那时起字符串被错误打印出来之前都可以,我不知道为什么。

我试图从我的电子邮件中提取单词,以便我可以训练分类器,但我被卡住了。

任何帮助将不胜感激。

Pri*_*ign 9

我需要使用 URl 安全 base64 解码。

我设法通过更改最后一行来使其正常工作:

print(base64.decodebytes(test))
Run Code Online (Sandbox Code Playgroud)

到:

print(base64.urlsafe_b64decode(test))
Run Code Online (Sandbox Code Playgroud)