Read mails from Outlook using python 4年前

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

平静的代表
天生我材必有用,千金散尽还复来。
4
发布数
0
关注者
2667
累计阅读

热门教程文档

React Native
40小节
10.x
88小节
Python
76小节
C++
73小节
Javascript
24小节
广告