我正在使用 Python 3.5 和imaplib
从 GMail 获取电子邮件并打印其正文。正文包含非 ASCII 字符。
这些以一种奇怪的方式“编码”,我不知道如何解决这个问题。
import email
import imaplib
c = imaplib.IMAP4_SSL('imap.gmail.com')
c.login('[email protected] /cdn-cgi/l/email-protection', 'password')
c.select('Inbox')
_, data = c.fetch(b'12345', '(RFC822)')
mail = data[0][1]
message = email.message_from_bytes(mail)
payload = message.get_payload()
body = mail[0].as_string()
print(body)
Gives
>> ... Mit freundlichen Gr=C3=BC=C3=9Fen ...
而不是想要的
>> ... Mit freundlichen Grüßen ...
在我看来,这不是编码问题,而是转换问题。但是我如何告诉 Python 正确转换字符呢?有没有比较方便的图书馆?
文本编码为带引号的可打印编码 https://en.wikipedia.org/wiki/Quoted-printable,这是一种对 ascii 文本中的非 ascii 字符进行编码的方法。您可以使用 python 对其进行解码quopri https://docs.python.org/3.7/library/quopri.html#module-quopri module.
>>> import quopri
>>> bs = b'Gr=C3=BC=C3=9Fen'
>>> # Decode quoted-printable to raw bytes.
>>> utf8 = quopri.decodestring(bs)
>>> # Decode bytes to text.
>>> s = utf8.decode('utf-8')
>>> print(s)
Grüßen
你可能会发现quoted-printable
是电子邮件的值content-transfer-encoding
header.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)