Python3从gmail读取正文

时间:2017-09-28 01:55:30

标签: python

我正在尝试使用python3来解析电子邮件,并在字符串列表中输出正文的内容。身体的内容总是遵循这种模式: string \ n string \ n string \ n等

我目前得到的错误是initial_value must be str or None, not bytes

import imaplib
import email
import time
import smtplib

from_email = "someemail@gmail.com"
from_pwd = "somepass"
smtp_server = "imap.gmail.com"
smtp_port= 993

def readmail(from_email,from_pwd,smtp_server,smtp_port ):
        try:
                mail = imaplib.IMAP4_SSL(smtp_server)
                mail.login(from_email,from_pwd)
                mail.select('inbox')
                result, data = mail.search(None, 'ALL')
                mail_ids = data[0]
                id_list = mail_ids.split()
                first_email_id =id_list[0]
                latest_email_id = id_list[-1] #most recent email
                result,data = mail.fetch(latest_email_id, "(RFC822)")
                raw_email = data[0][1]

                #read the email 
                email_message = email.message_from_string(raw_email)
                return email_message_instance.get_payload()
        except Exception as e:
                print(e)


print(readmail(from_email,from_pwd,smtp_server,smtp_port))

我知道错误发生在“#read the email”评论之后,因为我能够打印出raw_email

1 个答案:

答案 0 :(得分:1)

email.message_from_string()需要字符串参数。您可以使用 email.message_from_bytes()来解决此问题。

或者,您可以按以下方式将 raw_email 转换为字符串

mail_content = raw_email.decode('utf-8')

并在 email.message_from_string()

中传递 mail_content