0

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'])
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
David Vasandani
  • 1,840
  • 8
  • 30
  • 53

3 Answers3

9

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

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • Thank you for this. How would I tie this into a `for` loop for use in my code? I tried a couple things and it returned `{}`. – David Vasandani Nov 03 '12 at 19:34
  • 1
    @David `server.fetch` returns a dictionary of msg_id->things you asked for... so given `msgs = server.fetch(...)', you can do `for msg_id, stuff in msgs.iteritems()` – Jon Clements Nov 03 '12 at 19:39
0

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

eatonphil
  • 13,115
  • 27
  • 76
  • 133
0

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
Vladimir
  • 6,162
  • 2
  • 32
  • 36