使用IMAPClient如何查看邮件正文和发件人的电子邮件地址?
server = IMAPClient(imap_server, use_uid=True, ssl=ssl)
server.login(imap_user, imap_password)
print 'login successful'
select_info = server.select_folder('INBOX')
print '%d messages in INBOX' % select_info['EXISTS']
messages = server.search(['NOT DELETED'])
print "%d messages that aren't deleted" % len(messages)
print
print "Messages:"
response = server.fetch(messages, ['FLAGS', 'RFC822.SIZE'])
for msgid, data in response.iteritems():
print ' ID %d: %d bytes, flags=%s' % (msgid,
data['RFC822.SIZE'],
data['FLAGS'])
尽管IMAPClient
比使用imaplib
容易得多,但是了解IMAP protocol仍然很有用
((请注意,我已经选择了一个可以使用的任意电子邮件ID)
您可以通过以下方式获得FROM:
server.fetch([456], ['BODY[HEADER.FIELDS (FROM)]'])
# {456: {'BODY[HEADER.FIELDS (FROM)]': 'From: Facebook <[email protected]>\r\n\r\n', 'SEQ': 456}}
和身体通过:
server.fetch([456], ['BODY[TEXT]'])
# {456: {'BODY[TEXT]': "Hey Jon,\r\n\r\nYou recently entered a new contact email [snip]", 'SEQ': 456}}
但是,通常更容易做:
import email
m = server.fetch([456], ['RFC822'])
msg = email.message_from_string(m[456]['RFC822'])
print msg['from']
# Facebook <[email protected]>
from email.utils import parseaddr
print parseaddr(msg['from'])
# ('Facebook', '[email protected]')
print msg.get_payload()
# content of email...
仅需警惕有效载荷包括附件的位置或是多部分的...
这样发现消息正文(我将使用循环来打印每个未删除的消息正文):
for i in server[0].split():
body = server.fetch(i,"BODY[TEXT]")
print(body)
这应该在邮件正文中执行...
IMAPClient是一个相当底层的库,因此您仍然必须了解IMAP协议。
您可以尝试使用更多高级IMAP库:imap_tools