使用python从字符串中获取电子邮件ID的最佳方法

时间:2011-08-30 11:23:07

标签: python string

我们有什么方法可以使用python从下面的字符串中获取'X-Mailer-recipient:'电子邮件ID。

使用re?

    Received: from localhost6.localdomain6 (unknown [59.92.85.188])
        by smtp.webfaction.com (Postfix) with ESMTP id 05B332078BD1
        for <rshivaganesh@gmail.com>; Fri, 26 Aug 2011 04:59:36 -0500 (CDT)
    Content-Type: text/html; charset="utf-8"
    MIME-Version: 1.0
    Content-Transfer-Encoding: 7bit
    Subject: Test subject100
    From: shivaganesh@gmail.com
    To: rshivaganesh@gmail.com
    Date: Fri, 26 Aug 2011 10:01:39 -0000
    Message-ID: <20110826100139.4763.43322@localhost6.localdomain6>
    X-Mailer-status: false
    X-Mailer-recipient: rshivaganesh@gmail.com

由于

3 个答案:

答案 0 :(得分:4)

使用email包:

from email import message_from_string

msg = '''Received: from localhost6.localdomain6 (unknown [59.92.85.188])
    by smtp.webfaction.com (Postfix) with ESMTP id 05B332078BD1
    for <rshivaganesh@gmail.com>; Fri, 26 Aug 2011 04:59:36 -0500 (CDT)
Content-Type: text/html; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Subject: Test subject100
From: shivaganesh@gmail.com
To: rshivaganesh@gmail.com
Date: Fri, 26 Aug 2011 10:01:39 -0000
Message-ID: <20110826100139.4763.43322@localhost6.localdomain6>
X-Mailer-status: false
X-Mailer-recipient: rshivaganesh@gmail.com
'''
mail = message_from_string(msg)
print mail['x-mailer-recipient']

使用正则表达式不是一个好主意,因为a)标题名称不区分大小写,b)可以有多个具有相同名称的标题,c)一个标题可以包含另一个标题,例如有人可能会收到邮件地址“X-Mailer-recipient:@ hotmail.com”,这会混淆基于正则表达式的方法。

答案 1 :(得分:2)

使用正则表达式X-Mailer-recipient:\s*(.*)。您可以在Python中使用正则表达式here。您需要确保不会意外地将文字包含在您要查找的文本之外。例如,上面的正则表达式将匹配所有“X-Mailer-recipient:a@b.c BLARG BLARG BLARG”。然后,您需要访问所需的捕获组。

答案 2 :(得分:1)

您也可以使用以下内容:

d = """Received: from localhost6.localdomain6 (unknown [59.92.85.188]) by smtp.webfaction.com (Postfix) with ESMTP id 05B332078BD1 for <rshivaganesh@gmail.com>; Fri, 26 Aug 2011 04:59:36 -0500 (CDT) Content-Type: text/html; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Test subject100 From: shivaganesh@gmail.com To: rshivaganesh@gmail.com Date: Fri, 26 Aug 2011 10:01:39 -0000 Message-ID: <20110826100139.4763.43322@localhost6.localdomain6> X-Mailer-status: false X-Mailer-recipient: rshivaganesh@gmail.com"""

if 'X-Mailer-recipient:' in d:
    d.split('X-Mailer-recipient:')[1].split()[0]
>>> rshivaganesh@gmail.com