如何获取邮件正文?

问题描述 投票:0回答:1

我有这个代码,但我实际上没有收到电子邮件文本。

我必须解码电子邮件文本吗?

import sys
import imaplib
import getpass
import email
import email.header
from email.header import decode_header
import base64

def read(username, password, sender_of_interest):
    # Login to INBOX
    imap = imaplib.IMAP4_SSL("imap.mail.com", 993)
    imap.login(username, password)
    imap.select('INBOX')
    # Use search(), not status()
    # Print all unread messages from a certain sender of interest
    if sender_of_interest:
        status, response = imap.uid('search', None, 'UNSEEN', 'FROM {0}'.format(sender_of_interest))
    else:
        status, response = imap.uid('search', None, 'UNSEEN')
    if status == 'OK':
        unread_msg_nums = response[0].split()
    else:
        unread_msg_nums = []
    data_list = []
    for e_id in unread_msg_nums:
        data_dict = {}
        e_id = e_id.decode('utf-8')
        _, response = imap.uid('fetch', e_id, '(RFC822)')
        html = response[0][1].decode('utf-8')
        email_message = email.message_from_string(html)
        data_dict['mail_to'] = email_message['To']
        data_dict['mail_subject'] = email_message['Subject']
        data_dict['mail_from'] = email.utils.parseaddr(email_message['From'])
        #data_dict['body'] = email_message.get_payload()[0].get_payload()
        data_dict['body'] = email_message.get_payload()
        data_list.append(data_dict)
    print(data_list)
    # Mark them as seen
    #for e_id in unread_msg_nums:
        #imap.store(e_id, '+FLAGS', '\Seen')
    imap.logout()    
    return data_dict

所以我这样做:

print('Getting the email text bodiies ... ')
emailData = read(usermail, pw, sender_of_interest)
print('Got the data!')
for key in emailData.keys():
    print(key, emailData[key])

输出为:

mail_to [电子邮件受保护]
mail_subject 获取json文件
mail_from ('佩德罗·罗德里格斯', '[电子邮件受保护]')
身体[]

如何实际获取电子邮件文本?

email
1个回答
0
投票

根据“文本”的具体含义,您可能需要

get_body
方法。但是在达到这一点之前,您已经彻底修改了电子邮件。您从服务器收到的不是“HTML”,将其转换为字符串然后在其上调用
message_from_string
是迂回且容易出错的。你得到的是字节;直接使用
message_from_bytes
方法。 (这避免了当字节不是 UTF-8 时出现的各种问题;
message_from_string
方法只有在 Python 2 中才真正有意义,因为 Python 2 没有显式的
bytes
。)

from email.policy import default
...

        _, response = imap.uid(
            'fetch', e_id, '(RFC822)')
        email_message = email.message_from_bytes(
            response[0][1],
            policy=default)
        body = email_message.get_body(
            'html', 'text').get_payload(
            decode=True)

使用

policy
选择(不再非常)新的
EmailMessage
;您需要 Python 3.3+ 才能使用此功能。旧的
email.Message
类没有此方法,但由于许多其他原因,在新代码中也应避免使用此方法。

对于具有非平凡嵌套结构的多部分消息,这可能会失败;不带参数的

get_body
方法可以返回
multipart/alternative
消息部分,然后你必须从那里获取它。您还没有指定您的消息应该是什么样子,所以我不会进一步深入研究。

© www.soinside.com 2019 - 2024. All rights reserved.