我如何知道" From"一封电子邮件? (使用IMAP)

时间:2018-05-02 21:09:59

标签: python imap

在这种情况下,我从带有标准的电子邮件中下载纯文本,
但我怎么知道发送它的@ gmail.com地址。 我使用的是Python 3.5.4

import imaplib
import email

mail = imaplib.IMAP4_SSL('imap.gmail.com')
#imaplib module implements connection based on IMAPv4 protocol
mail.login('myemail', 'mypassword')


mail.list() # Lists all labels in GMail
mail.select('inbox') # Connected to inbox.


result, data = mail.uid('search', None, '(HEADER Subject "[News]")')
#search and return uids instead
i = len(data[0].split()) # data[0] is a space separate string
for x in range(i):
   latest_email_uid = data[0].split()[x] # unique ids wrt label selected
   result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)')
   # fetch the email body (RFC822) for the given ID
   raw_email = email_data[0][1]

 #From = email.utils.parseaddr(email_data['From'])
 #continue inside the same for loop as above
raw_email_string = raw_email.decode('utf-8')
# converts byte literal to string removing b''
email_message = email.message_from_string(raw_email_string)
#this will loop through all the available multiparts in mail
for part in email_message.walk():
 if part.get_content_type() == "text/plain": # ignore attachments/html
     enter code here`body = part.get_payload(decode=True)
     save_string = str("Llave de amigo" + str(x) + str("a"))
     # location on disk
     myfile = open(save_string, 'a')
     myfile.write(body.decode('utf-8'))
     # body is again a byte literal
     myfile.close()

1 个答案:

答案 0 :(得分:0)

documentation(假设Python 2.7)可能并不明显,但是通过实现dict函数,email_message对象就像__getitem__一样。由于您获取并解析了整个消息,因此您应该能够以下列方式访问它:

email_message['from']

注意,这为您提供了标题的原始表示,在很多情况下可能没问题。

然后,您可能希望使用email.utils.parseaddr将其分解为组成部分:

realname, addr = email.utils.parseaddr(email_message['from')).
如果您随后使用多个收件人解析To或Cc标头,

email.utils.getaddresses可能会有用。

如果您需要在旧版本的Python中处理国际化标头,可以使用email.header.decode_headeremail.header.make_header

在Python3.6中,这已经改变significantly,应该更直接。