Read mails from Outlook using python

code as following:

import win32com.client, sqlite3
from datetime import datetime

def collectMail():
    conn = sqlite3.connect('outlook.db')
    i = 0
    try:    
        outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

        inbox = outlook.GetDefaultFolder(6) 
        messages = inbox.Items
        print 'total messages: ', len(messages)
        message = messages.GetFirst ()
        while message:
            i += 1          
            try:
                subject = message.Subject
                #print i, subject

                received_time = str(message.ReceivedTime)
                #print received_time
                received_time = datetime.strptime(received_time, '%m/%d/%y %H:%M:%S') 
                #print message.EntryID
                html_body = message.HTMLBody
                size = long(message.Size)

                sender =  message.SenderName
                receiver = message.To
                cc = message.Cc
                body = message.Body         
                conn.execute('insert into outlook(SUBJECT, SENDER, RECEIVER, CC, SIZE, RECEIVED_TIME, BODY, HTML_BODY) values(?, ?, ?, ?, ?, ?, ?, ?)', (subject, sender, receiver, cc, size, received_time, body, html_body))
                conn.commit()
            except:
                print i, 'skip'
                continue                

            message = messages.GetNext()            
    finally:
        print 'connection closed'
        conn.close()


collectMail()

'''
sql to create table

create table outlook(
ID INTEGER PRIMARY KEY   AUTOINCREMENT,
SUBJECT VARCHAR(200) NOT NULL,
SENDER VARCHAR(200) NOT NULL,
RECEIVER VARCHAR(200) NOT NULL,
CC  VARCHAR(200) NOT NULL,
SIZE LONG NOT NULL,
RECEIVED_TIME DATETIME,
BODY TEXT,
HTML_BODY TEXT);
'''

python-script-to-read-the-emails-from-custom-folder-from-microsoft-outlook-mailb
reading-e-mails-from-outlook-with-python-through-mapi
microsoft.office.interop.outlook
sqlite_using_autoincrement

你可能感兴趣的:(Read mails from Outlook using python)