我正在使用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)
通过Google的设置,可以通过安全性较低的应用访问此电子邮件。无论如何,当您使用自己的凭据运行它时,会得到很大的文本块。旁注告诉您什么是什么,脚本中的引号提醒我事情在哪里:
# {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'',但是它不起作用。它只是完全打印出来。如何正式打印?
答案 0 :(得分:0)
imapclient docs演示了如何使用Python的email包创建电子邮件对象:
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部分。