使用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'])
答案 0 :(得分:9)
虽然IMAPClient
比使用imaplib
容易得多,但了解IMAP protocol
(注意,我选择了一个任意的单个电子邮件ID)
您可以通过以下方式获取FROM:
server.fetch([456], ['BODY[HEADER.FIELDS (FROM)]'])
# {456: {'BODY[HEADER.FIELDS (FROM)]': 'From: Facebook <register+mr4k25sa@facebookmail.com>\r\n\r\n', 'SEQ': 456}}
和BODY经过:
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 <register+mr4k25sa@facebookmail.com>
from email.utils import parseaddr
print parseaddr(msg['from'])
# ('Facebook', 'register+mr4k25sa@facebookmail.com')
print msg.get_payload()
# content of email...
请注意有效负载包含附件的位置或是多部分......
答案 1 :(得分:0)
for i in server[0].split():
body = server.fetch(i,"BODY[TEXT]")
print(body)
这应该为邮件正文...
答案 2 :(得分:0)
IMAPClient是一个相当底层的库,因此您仍然必须了解IMAP协议。
您可以尝试使用更多高级IMAP库:imap_tools