Using IMAPClient how do I view the message body and the senders email address?
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'])
Although IMAPClient
is a lot easier than using imaplib
, it's still useful to know about the IMAP protocol
(Note, I've picked an arbitrary single email id to work with)
You can get the FROM via:
server.fetch([456], ['BODY[HEADER.FIELDS (FROM)]'])
# {456: {'BODY[HEADER.FIELDS (FROM)]': 'From: Facebook <register+mr4k25sa@facebookmail.com>\r\n\r\n', 'SEQ': 456}}
And the BODY via:
server.fetch([456], ['BODY[TEXT]'])
# {456: {'BODY[TEXT]': "Hey Jon,\r\n\r\nYou recently entered a new contact email [snip]", 'SEQ': 456}}
However, what's generally easier is to do:
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...
Just be wary of where the payload includes attachments or is multipart...