Question

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'])
Was it helpful?

Solution

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...

OTHER TIPS

message body is found like this (im going to use a loop to get print each not deleted message body):

  for i in server[0].split():
      body = server.fetch(i,"BODY[TEXT]")
      print(body)

This should do it for the message body...

IMAPClient is a fairly low-level lib, so you are still must to know IMAP protocol.

You can try to use more high level IMAP library: imap_tools

  • Parsed email message attributes
  • Query builder for searching emails
  • Work with emails in folders (copy, delete, flag, move, seen)
  • Work with mailbox folders (list, set, get, create, exists, rename, delete, status)
  • No dependencies
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top