python - Gmail API - 使用 'raw' 输出并解码为 utf-8 查看奇怪的德语字符

标签 python python-3.x gmail-api

我在使用 Gmail API 阅读电子邮件时遇到一些编码问题。 首先我使用这个检索电子邮件:

message = service.users().messages().get(userId='me', id='169481bce75af185', format='raw').execute()

之后我使用这些行从中获取一个字符串并将其转换为 mime 消息:

msg_str = str(base64.urlsafe_b64decode(message['raw'].encode('utf-8')).decode('utf-8'))
mime_msg = email.message_from_string(msg_str)

然后我打印我得到的:

print(mime_msg.get_payload()[0])

但是我可以在输出中看到一些奇怪的字符,例如:

Gesch=C3=A4ftsf=C3=BChrer

在邮件标题中我可以看到:

Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable

我做错了什么,如何在没有奇怪字符的情况下获得正确的输出?

谢谢你的时间

最佳答案

您的数据已被编码为 UTF-8,然后通过进一步编码为 quoted-printable 使 7 位传输安全。这就是邮件标题告诉您的内容。使用 quopri 撤消 quoted-printable 然后使用 .decode 获取 Unicode:

>>> import quopri
>>> print(quopri.decodestring("Gesch=C3=A4ftsf=C3=BChrer").decode("utf-8"))
Geschäftsführer

关于python - Gmail API - 使用 'raw' 输出并解码为 utf-8 查看奇怪的德语字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54981406/

相关文章:

python - 使用 rpy2 导入并使用 R 'heavy' 包

python - 值错误 : cannot reindex from a duplicate axis when assigning new column to pandas DataFrame

node.js - gmail API 快速入门在 google.gmail ('v1' 处失败)

gmail-api - Gmail REST API获取消息功能返回无效的historyId

Google Cloud 函数使用服务帐户域范围访问调用 Gmail API

python - 如何使用 matplotlib 从字典中绘制水平条形图?

python - 转换列表的格式

java - 类、方法、实例创建和 Main 相当于 Python 中的 Java

python - Matplotlib 在子图中的条形上打印值

python - python 安装中的文件模块失败