尝试使用pythonista从gmail阅读电子邮件

时间:2015-01-07 21:31:14

标签: python email unicode gmail-imap

我是Python的新手,我很高兴能够使用imap4访问gmail

这是我用来访问电子邮件的代码:

from __future__ import print_function
import getpass
import imaplib
import console
import collections
import re
import email
import codecs
import quopri

console.clear()
mail = imaplib.IMAP4_SSL('imap.gmail.com',993)
my password = getpass.getpass("Password: ")
address = 'sch.e@gmail.com'
print('Which email address (TO) would you like to search: ',end='')
EE = raw_input()
SS = r"(TO "+"\""+EE+"\""+r")"
mail.login(address, mypassword)
mail.select("inbox")  #select the box on gmail
print("Checking for e-mails TO ",EE)
typ, messageIDs = mail.search(None,'(SINCE "01-Jan-2014")',SS)
MIDs=messageIDs[0].split()
for mailid in MIDs[::-1]:
    resp, data = mail.fetch(mailid,'(RFC822)')
    raw_body=data[0][1]
    print(raw_body.decode('UTF-8','strict'))
    print(quopri.encodestring(raw_body))
    msg=email.message_from_string(raw_body)
    print(msg)

不幸的是,没有一个打印语句包含正确的Umlaute。

(例如BesteGrüße)

有人可以给我一个如何处理编码的提示吗?它看起来像Utf-8编码的文本,除了“=”字符,

谢谢!! 埃里克

1 个答案:

答案 0 :(得分:0)

电子邮件的正文已被字符集编码为字节,然后使用MIME的quoted-printable算法编码为7位ASCII。您将必须反转QP编码以获取原始字节,然后您可以使用电子邮件的字符集(不是utf-8)将它们转换为字符串,否则QP编码的文本将改为Beste Gr=C3=BC=C3=9Fe 。字符集更有可能iso-8859-1)。电子邮件标题将告诉您实际的字符集,以及正文的编码方式(QP,base64等)。但是,您只提取电子邮件正文,因此您还需要使用RFC822.HEADER来获取电子邮件标题。

我们假设使用ISO-8859-1将电子邮件编码为quoted-printable(获取要验证的电子邮件标头)。尝试更像这样解码它:

raw_body=data[0][1]
raw_body=quopri.decodestring(raw_body)
raw_body=raw_body.decode('ISO-8859-1')
相关问题