Python 我怎么知道“我怎么知道”呢;从「;一封电子邮件?(使用IMAP)

Python 我怎么知道“我怎么知道”呢;从「;一封电子邮件?(使用IMAP),python,imap,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.l

在这种情况下,我从一封电子邮件中下载纯文本,标准为,
但是我怎么知道是谁发的@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()

这在(假设Python 2.7)中可能并不明显,但email\u message对象通过实现
\uuu getitem\uuu
函数起着类似于dict的作用。由于您获取并解析了整个消息,因此您应该能够通过以下方式访问它:

email_message['from']
注意,这为您提供了标题的原始表示,在很多情况下这可能是可以的

然后,您可能希望使用将其分解为多个组成部分:

realname, addr = email.utils.parseaddr(email_message['from')).
email.utils.getaddresses
如果您随后解析到或抄送多个收件人的邮件头,可能会很有用

如果您需要在较旧版本的Python中处理国际化的头文件,
email.header.decode\u header
可以使用

在Python3.6中,这一点已经改变,应该更简单