I'm trying to retrieve my emails from our imap server and found that using imaplib is the way to do that. So I found this link https://gist.github.com/robulouski/7441883 that shows the basics on how to use imaplib. I followed the code and changed some of the values respectively so I can login on my email account.
Im still trying to learn but so far this is the modified code that I have:
import sys
import imaplib
import getpass
import email
import datetime
email_address = 'test@companyemail.net'
password = 1234
M = imaplib.IMAP4('mail.companyemail.net')
try:
M.login(email_address, password)
print "LOGIN SUCCESS!"
except imaplib.IMAP4.error:
print "LOGIN FAILED!!"
# ... exit or deal with failure...
def process_mailbox(M):
rv, data = M.search(None, "ALL")
if rv != 'OK':
print "No messages found!"
return
for num in data[0].split():
rv, data = M.fetch(num, '(RFC822)')
if rv != 'OK':
print "ERROR getting message", num
return
msg = email.message_from_string(data[0][1])
print 'Message %s: %s' % (num, msg['Subject'])
#print 'Raw Date:', msg['Date']
date_tuple = email.utils.parsedate_tz(msg['Date'])
if date_tuple:
local_date = datetime.datetime.fromtimestamp(
email.utils.mktime_tz(date_tuple))
print "Local Date:", \
local_date.strftime("%a, %d %b %Y %H:%M:%S")
rv, data = M.select("INBOX")
if rv == 'OK':
print "Processing mailbox...\n"
process_mailbox(M)
The output of the the code above is:
OK ['Logged in']
Processing mailbox...
Message 1: test
Raw Date: Fri, 05 Aug 2016 05:38:17 +0800
Local Date: Thu, 04 Aug 2016 14:38:17
Message 2: test email 2
Raw Date: Thu, 4 Aug 2016 14:48:35 -0700
Local Date: Thu, 04 Aug 2016 14:48:35
Message 3: test email 3
Raw Date: Fri, 05 Aug 2016 05:52:33 +0800
Local Date: Thu, 04 Aug 2016 14:52:33
Message 4: Fwd: test email 2
Raw Date: Fri, 05 Aug 2016 05:54:54 +0800
Local Date: Thu, 04 Aug 2016 14:54:54
Message 5: test
Raw Date: Wed, 10 Aug 2016 05:28:02 +0800
Local Date: Tue, 09 Aug 2016 14:28:02
I was wondering if it would be possible to output it in a table format so it would look like:
| Message | Raw Date | Local Date |
| test | Fri, 05 Aug 2016 05:38:17 +0800 | Thu, 04 Aug 2016 14:38:17 |
| test email 2 | Thu, 4 Aug 2016 14:48:35 -0700 | Thu, 04 Aug 2016 14:48:35 |
and so on...
Thank you for your help. :)