1

我一直在尝试解决这个问题,并在 stackoverflow 和其他地方找到解决方案,但我无法得到它(我猜 Python 经验不足),所以请帮忙:

我在 Python 中使用 imaplib 和电子邮件库从我的 gmail 帐户获取电子邮件。我可以登录并找到我想要的邮件,并且我已经实现了捕获多部分电子邮件的脚本,但是电子邮件正文的输出文本(通过 get_payload 方法)是一个字符串,我想获取正文发送的电子邮件,以便每个新行(作为字符串)被分隔并存储到一个列表中。请查看我的代码部分:

    mail = imaplib.IMAP4_SSL('imap.gmail.com', 993)
    mail.login('mymail@gmail.com', 'password')
    mail.select("inbox")
    date = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%d-%b-%Y")
    result, data = mail.uid('search', 'UNSEEN', '(SENTSINCE {date} FROM "someone@gmail.com")'.format(date=date))
    latest_email_uid = data[0].split()[-1]
    result, data = mail.uid('fetch', latest_email_uid, '(RFC822)')
    raw_email = data[0][1]
    email_message = email.message_from_string(raw_email)
    text = ''
    if email_message.is_multipart():
            html = None
            for part in email_message.get_payload():
                if part.get_content_charset() is None:
                    text = part.get_payload(decode=True)
                    continue
                charset = part.get_content_charset()
                if part.get_content_type() == 'text/plain':
                    text = unicode(part.get_payload(decode=True), str(charset), "ignore").encode('windows-1250', 'replace')
                if part.get_content_type() == 'text/html':
                    html = unicode(part.get_payload(decode=True), str(charset), "ignore").encode('windows-1250', 'replace')
            if text is not None:
                text.strip()
            else:
                html.strip()
    else:
        text = unicode(email_message.get_payload(decode=True), email_message.get_content_charset(), 'ignore').encode('windows-1250', 'replace')
        text.strip()
    print text

事先我有更多代码,顶部是运行代码所需的导入库,因此无需检查。我试图声明 text = [],我试图不剥离()文本或 html,.. 但我就是无法得到它。有没有一种简单的方法可以在发送时获取正文的文本,每个字符串都在自己的行中?我觉得它很简单,但我不明白..提前谢谢!!

4

0 回答 0