username = "email address"
password = "123"
conn = imaplib.IMAP4_SSL(imap_server)
try:
(retcode, capabilities) = conn.login(username, password)
except:
print sys.exc_info()[1], "failed to login as %s" % username
sys.exit(1)
conn.select() # Select inbox or default namespace
'''
alternative to default inbox
#print conn.list() # see list of possible boxes
conn.select("[Gmail]/Sent Mail", readonly=1)
'''
(retcode, messages) = conn.search(None, '(UNSEEN)')
if retcode == 'OK' and messages[0] > '':
for num in messages[0].split(' '):
print 'Processing :', num
typ, data = conn.fetch(num,'(RFC822)')
msg = email.message_from_string(data[0][1])
sender = email.utils.parseaddr(msg['From'])
recipient = email.utils.parseaddr(msg['To'])
from_email = extract_email(sender)
to_email = extract_email(recipient)
subject = msg['Subject']
body = get_body(msg.get_payload())
message, created = Message.objects.get_or_create(mail_id = msg['Message-ID'])
if created or not message['subject']:
message.subject = subject
message.body = body
message.from_email = from_email
message.to_email = to_email
message.mail_date = localtime(dateutil.parser.parse(msg["Date"]))
message.save()
# mark as seen if item was created ok
#if result['app_item_id'] > 0:
# typ, data = conn.store(num,'-FLAGS','\\Seen')
else:
print "Nothing to process"
conn.close()
A Later version used uid instead of sequential numbering, returning both a unique message id and thread id
typ, data = conn.uid('fetch', uid,'(RFC822 X-GM-MSGID X-GM-THRID)')
# this is only available for gmail and assumes data always returned in similar order
# string for data[0][0] = '1 (X-GM-THRID 1444702053679861808 X-GM-MSGID 1444702053679861808 UID 1 RFC822 {724}'
idlist = data[0][0][3:].split(' ')
id = {}
id[idlist[0]] = idlist[1]
id[idlist[2]] = idlist[3]
id[idlist[4]] = idlist[5]
Hope this helps.
Phoebe.