Bar*_*ar6 2 python api gmail encoding quoted-printable
我有个问题。我正在尝试使用 gmail api 读取来自 gmail 的电子邮件。我按照这里的说明进行操作https://developers.google.com/gmail/api/v1/reference/users/messages/get
\n\n我做了一些更改以在 python 3 上运行它,所以我最终得到了以下代码:
\n\ndef GetMimeMessage(service, user_id, msg_id):\ntry:\n message = service.users().messages().get(userId=user_id, id=msg_id,\n format=\'raw\').execute()\n\n print (\'Message snippet: %s\' % message[\'snippet\'])\n msg_str = base64.urlsafe_b64decode(message[\'raw\'].encode(\'utf8\'))\n mime_msg = email.message_from_bytes(msg_str)\n print(mime_msg)\n\n return mime_msg\nexcept errors.HttpError as error:\n print (\'An error occurred: %s\' % error)\nRun Code Online (Sandbox Code Playgroud)\n\n现在输出非常接近我想要的结果,但有一个问题是输出中的匈牙利重音字符很奇怪:\nG=C3=A1bor而不是G\xc3\xa1bor
而且 html 标签也被破坏了:
\n\nFollow us: =09=09=09=09=09=09=09=09=09<a href=3D"http=\nRun Code Online (Sandbox Code Playgroud)\n\n我已经发现这与消息的编码方式有关,请参阅电子邮件标题:
\n\nContent-Type: text/html; charset=UTF-8\nContent-Transfer-Encoding: quoted-printable\nRun Code Online (Sandbox Code Playgroud)\n\n问题是,我似乎找不到正确解码它的方法。感谢任何帮助。
\n小智 5
经过几个小时的努力解决同样的问题,我终于找到了解决方案(至少对于我的情况)。即使该线程很旧,我也会将其发布在这里,以便其他人以后可以找到它。事情是这样的:
# Get your message
message = service.users().messages().get(userId=user_id, id=msg_id, format='full').execute()
# Get the right body data item (this part was my Heureka-moment as there are several 'data' keys)
content = message['payload']['parts'][0]['parts'][1]['body']['data']
# Encode
msg_body = base64.urlsafe_b64decode(content).decode('utf-8')
Run Code Online (Sandbox Code Playgroud)
这个序列让解码/编码对我有用。关于 Base64 和 Google Gmail API 的解码/编码问题的线程有很多不同的解决方案建议,但似乎每种情况都是独一无二的。希望这个解决方案也能帮助您!
| 归档时间: |
|
| 查看次数: |
1864 次 |
| 最近记录: |