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

tim*_*mbo 4 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()
Run Code Online (Sandbox Code Playgroud)

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

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

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

sna*_*erb 7

如果您使用的是Python3.6或更高版本,您可以使用该email.message.Message.get_content()方法自动解码文本。此方法取代get_payload(),但get_payload()仍然可用。

\n\n

假设您有一个s包含此电子邮件的字符串(基于文档中的示例):

\n\n
Subject: Ayons asperges pour le =?utf-8?q?d=C3=A9jeuner?=\nFrom: =?utf-8?q?Pep=C3=A9?= Le Pew <pepe@example.com>\nTo: Penelope Pussycat <penelope@example.com>,\n Fabrette Pussycat <fabrette@example.com>\nContent-Type: text/plain; charset="utf-8"\nContent-Transfer-Encoding: quoted-printable\nMIME-Version: 1.0\n\n    Salut!\n\n    Cela ressemble =C3=A0 un excellent recipie[1] d=C3=A9jeuner.\n\n    [1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718\n\n    --Pep=C3=A9\n   =20\n
Run Code Online (Sandbox Code Playgroud)\n\n

字符串中的非 ASCII 字符已使用标头quoted-printable中指定的编码进行编码Content-Transfer-Encoding

\n\n

创建电子邮件对象:

\n\n
import email\nfrom email import policy\n\nmsg = email.message_from_string(s, policy=policy.default)\n
Run Code Online (Sandbox Code Playgroud)\n\n

这里需要设置策略;否则policy.compat32使用,它返回一个没有 get_content 方法的旧 Message 实例。 policy.default最终将成为默认策略,但从 Python3.7 开始它仍然是policy.compat32.

\n\n

get_content()方法自动处理解码:

\n\n
print(msg.get_content())\n\nSalut!\n\nCela ressemble \xc3\xa0 un excellent recipie[1] d\xc3\xa9jeuner.\n\n[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718\n\n--Pep\xc3\xa9\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果您有多部分消息,get_content()则需要对各个部分进行调用,如下所示:

\n\n
for part in message.iter_parts():\n    print(part.get_content())\n
Run Code Online (Sandbox Code Playgroud)\n


And*_*Dog 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)
Run Code Online (Sandbox Code Playgroud)

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