2013-07-27 37 views
0

有人可以告訴我如何從Python中的email.message_from_string()獲取from地址嗎?謝謝!我試過從Python中的message_from_string()獲取地址

message = email.message_from_string(email_text) 
from = message['From'] 

但是,這似乎沒有工作。

這裏是我解析電子郵件:

Received: (qmail 16903 invoked by uid 30297); 27 Jul 2013 15:16:51 -0000 
Received: from unknown (HELO p3pismtp01-015.prod.phx3.secureserver.net) ([10.6.12.15]) 
      (envelope-sender <[email protected]>) 
      by p3plsmtp10-03.prod.phx3.secureserver.net (qmail-1.03) with SMTP 
      for <[email protected]>; 27 Jul 2013 15:16:51 -0000 
X-IronPort-Anti-Spam-Result: AkYDACPh81FKfVKyk2dsb2JhbABbgkQCgUVUvQmBEAgWDgEBAQEHCwsJFAQkghsJAQEEAUABGx4DAQsGBQEBAQECBQM4IgERAQUBHAYTh30BAwkGmxaMT4J/hBcKGScNZId0AQUMj3iEBQOXX49nFimDAYFVIA 
Received: from mail-we0-f178.google.com ([74.125.82.178]) 
    by p3pismtp01-015.prod.phx3.secureserver.net with ESMTP; 27 Jul 2013 08:16:51 -0700 
Received: by mail-we0-f178.google.com with SMTP id u57so2691391wes.23 
     for <[email protected]>; Sat, 27 Jul 2013 08:16:50 -0700 (PDT) 
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; 
     d=gmail.com; s=20120113; 
     h=mime-version:in-reply-to:references:date:message-id:subject:from:to 
     :content-type; 
     bh=yU9O8/uUeQbclKzg3n9YD5bu4chhx/D44TL6gOzd2ag=; 
     b=aFXVUYwpBwvVfAzzTQSbpAIR1rbMq/I32DPy1DFLpgqgbtIrmUCbp/EQJyvqupxXSe 
     chZmaH7ALuMurnlTbpjOLqHBZx550U9gmYl/+tk6Ql7HgYOsYW+0eIpeyWGfgAlgyz3O 
     ISyiKyjhjLVs6Cw01LJW9n2zgssNqcE8uMqpqnVagl33bbKbI3ODWCvnmjhfwQBVHhjm 
     /CMXJ1dUIfcleFHRdH26lWBEm2Z54dYe06EPwJ6zF7LGFRBakF120kY+gUXpnrlfwZi9 
     XyFevTI6lvL6+W28b8fxUisGzfL9zmvPb9wHyOpHix5kuvj06Z3FvFhIer03La/Fhd7k 
     EWtA== 
MIME-Version: 1.0 
X-Received: by 10.180.20.228 with SMTP id q4mr2165577wie.60.1374938210558; 
Sat, 27 Jul 2013 08:16:50 -0700 (PDT) 
Received: by 10.216.164.9 with HTTP; Sat, 27 Jul 2013 08:16:50 -0700 (PDT) 
In-Reply-To: <[email protected]rillapp.com> 
References: <[email protected]rillapp.com> 
Date: Sat, 27 Jul 2013 11:16:50 -0400 
Message-ID: <[email protected]om> 
Subject: Re: New message regarding your stay on 2013-06-19 to 2013-06-29 at 
the The Marriot <SRID2> 
From: Taylor Lovett <[email protected]> 
To: Taylor Lovett <[email protected]> 
Content-Type: multipart/alternative; boundary=f46d04218485a0ea0404e27fbf5b 
X-Nonspam: None 

--f46d04218485a0ea0404e27fbf5b 
Content-Type: text/plain; charset=ISO-8859-1 

Test email! 

--f46d04218485a0ea0404e27fbf5b 
Content-Type: text/html; charset=ISO-8859-1 

回答

2

from是保留關鍵字。使用不同的變量名稱。您的代碼否則工作正常:

>>> import email 
>>> message = email.message_from_string(email_text) 
>>> message['From'] 
'Taylor Lovett <[email protected]>' 
>>> from = message['From'] 
    File "<stdin>", line 1 
    from = message['From'] 
     ^
SyntaxError: invalid syntax 
>>> from_address = message['From'] 
>>> from_address 
'Taylor Lovett <[email protected]>'