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