我该如何阅读其中任何邮件的正文?方式
我尝试过这个:
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(email_user, email_pass)
mail.select('Inbox')
type, data = mail.search(None, 'ALL')
mail_ids = data[0]
id_list = mail_ids.split()
for num in data[0].split():
typ, data = mail.fetch(num, '(RFC822)' )
raw_email = data[0][1] # converts byte literal to string removing b''
raw_email_string = raw_email.decode('utf-8')
email_message = email.message_from_string(raw_email_string)
subject = str(email_message).split("Subject: ", 1)[1].split("\nTo:", 1)[0]
#body = str(email_message).split("body: ", 1)[1].split("\nTo:", 1)[0]
print(email_message);
如果只想解析电子邮件并访问正文,请考虑使用mail-parser。这是一个简单的邮件解析器,将原始电子邮件作为输入并生成已解析的对象。
import mailparser
mail = mailparser.parse_from_file(f)
mail = mailparser.parse_from_file_obj(fp)
mail = mailparser.parse_from_string(raw_mail)
mail = mailparser.parse_from_bytes(byte_mail)
使用方法:
mail.body #use this to access the body contents
mail.to