0

我正在使用 python3,并且使用我的电子邮件凭据,此函数会打印一个似乎分为正式部分的文本块。这是我阅读电子邮件的代码:

import pprint
import imapclient

# Email = Your email
# Password = Your password
# folder = just type '[Gmail]/All Mail'.
# readonly = Tell wether emails are marked as read or not when you read them here.
# search = Search term for gmail. Can be empty by typing ''.
def ReadEmail(Email, Password, folder, readonly, search):
    imapObj = imapclient.IMAPClient('imap.gmail.com', ssl=True)
    imapObj.login(' ' + Email + ' ', ' ' + Password + ' ')
    pprint.pprint(imapObj.list_folders())
    imapObj.select_folder(str(folder), readonly=readonly)
    UIDs = imapObj.gmail_search(str(search))
    rawMessages = imapObj.fetch(UIDs, ['BODY[]'])
    pprint.pprint(rawMessages)

顺便说一句,通过谷歌的设置,可以通过不太安全的应用程序访问此电子邮件。无论如何,当你用你的凭据运行它时,你会得到这么一大块文本。旁注告诉你什么是什么,我的脚本中有引号提醒我事情在哪里:

                #    {1: {b'BODY[]': b'Bcc: thedestoryer11@gmail.com\r\nReturn-Path: '      <<< Receiver's email
                #               b'<noreply.smtp.supermechm500@gmail.com>\r\nRece'           <<< Sender of an email
                #               b'ived: from [127.0.0.1] (ec2-23-21-200-247.comput'
                #               b'e-1.amazonaws.com. [23.21.200.247])\r\n       '
                #               b' by smtp.gmail.com with ESMTPSA id 24-v6sm169089'         <<< Sent using...
                #               b'38qts.19.2018.11.14.16.31.38\r\n        for <t'
                #               b'hedestoryer11@gmail.com>\r\n        (version=T'           <<< Reciever of the email
                #               b'LS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=12'
                #               b'8/128);\r\n        Wed, 14 Nov 2018 16:31:38 -'
                #               b'0800 (PST)\r\nMessage-ID: <5becbe6a.1c69fb81.4'
                #               b'af4f.c041@mx.google.com>\r\nDate: Wed, 14 Nov '           <<< Date Received
                #               b'2018 16:31:38 -0800 (PST)\r\nFrom: noreply.smt'
                #               b'p.supermechm500@gmail.com\r\n\r\nTesting from SM'         <<< Message (Will not contain buttons or images. Check your email application for these media
                #               b'TP +-+\r\n',

我可以在其中看到 \n、\r 和 b'' 但它不起作用。它只是完全打印出来的。我如何正式打印这个?

4

1 回答 1

0

imapclient文档演示了如何使用 Python 的电子邮件包创建电子邮件消息对象:

import email

for uid, message_data in server.fetch(messages, 'RFC822').items():
    email_message = email.message_from_bytes(message_data[b'RFC822'])
    print(uid, email_message.get('From'), email_message.get('Subject'))

如果你想打印一条完整的消息,你可以这样做

print(email_message)

email.message.EmailMessage类提供了各种方法来访问消息的不同部分,例如标题、正文、mime 部分。

于 2019-03-16T09:26:48.223 回答