Python电子邮件引用 - 可打印编码问题

时间:2010-10-28 05:37:56

标签: python email encoding imaplib

我使用以下内容从Gmail中提取电子邮件:

def getMsgs():
 try:
    conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
  except:
    print 'Failed to connect'
    print 'Is your internet connection working?'
    sys.exit()
  try:
    conn.login(username, password)
  except:
    print 'Failed to login'
    print 'Is the username and password correct?'
    sys.exit()

  conn.select('Inbox')
  # typ, data = conn.search(None, '(UNSEEN SUBJECT "%s")' % subject)
  typ, data = conn.search(None, '(SUBJECT "%s")' % subject)
  for num in data[0].split():
    typ, data = conn.fetch(num, '(RFC822)')
    msg = email.message_from_string(data[0][1])
    yield walkMsg(msg)

def walkMsg(msg):
  for part in msg.walk():
    if part.get_content_type() != "text/plain":
      continue
    return part.get_payload()

然而,我得到的一些电子邮件几乎不可能从编码相关的字符(如'=')中提取日期(使用正则表达式),随机落在各种文本字段的中间。这是一个例子,它出现在我想要提取的日期范围内:

  

姓名:KIRSTI电邮:   kirsti@blah.blah电话号码:+ 999   99995192派对总计:4总计,0   儿童抵达/离开:10月9日=   ,   2010年 - 2010年10月13日 - 2010年10月13日

有没有办法删除这些编码字符?

3 个答案:

答案 0 :(得分:5)

你可以/应该使用email.parser模块来解码邮件消息,例如(快速而肮脏的例子!):

from email.parser import FeedParser
f = FeedParser()
f.feed("<insert mail message here, including all headers>")
rootMessage = f.close()

# Now you can access the message and its submessages (if it's multipart)
print rootMessage.is_multipart()

# Or check for errors
print rootMessage.defects

# If it's a multipart message, you can get the first submessage and then its payload
# (i.e. content) like so:
rootMessage.get_payload(0).get_payload(decode=True)

使用Message.get_payload的“decode”参数,模块会自动解码内容,具体取决于其编码方式(例如问题中的引用的printables)。

答案 1 :(得分:2)

这就是所谓的引用可打印编码。您可能希望使用quopri.decodestring - http://docs.python.org/library/quopri.html

之类的内容

答案 2 :(得分:0)

如果您使用的是Python3.6或更高版本,则可以使用print方法自动解码文本。尽管socket仍然可用,但是该方法取代了get_payload()

假设您有一个包含此电子邮件消息的字符串get_payload()(基于文档中的email.message.Message.get_content()

s

已按照Subject: Ayons asperges pour le =?utf-8?q?d=C3=A9jeuner?= From: =?utf-8?q?Pep=C3=A9?= Le Pew <pepe@example.com> To: Penelope Pussycat <penelope@example.com>, Fabrette Pussycat <fabrette@example.com> Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable MIME-Version: 1.0 Salut! Cela ressemble =C3=A0 un excellent recipie[1] d=C3=A9jeuner. [1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718 --Pep=C3=A9 =20 标头中指定的quoted-printable编码对字符串中的非ASCII字符进行了编码。

创建电子邮件对象:

Content-Transfer-Encoding

此处需要设置策略;否则,将使用examples,它返回不具有get_content方法的旧式Message实例。 policy.compat32最终将成为默认策略,但是从Python3.7开始,它仍为import email from email import policy msg = email.message_from_string(s, policy=policy.default)

policy.compat32方法自动处理解码:

get_content()

如果您有多部分消息,则需要在各个部分上调用print(msg.get_content()) Salut! Cela ressemble à un excellent recipie[1] déjeuner. [1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718 --Pepé ,如下所示:

get_content()