使用win32com接口獲取outlook收件箱的內容


環境准備:

1.安裝pywin32安裝包,https://sourceforge.net/projects/pywin32/files/pywin32/Build%20221/

2.本地使用的outlook 2013

#encoding=utf-8

import win32com.client, sqlite3
from datetime import datetime

def collectMail():
conn = sqlite3.connect(r'D:\Software\SQLiteSpy_1.9.9\outlook.db')
i = 0
try:

#啟動outlook進程
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
#獲取收件箱實例
inbox = outlook.GetDefaultFolder(6)

#逐條處理郵件信息
messages = inbox.Items
print 'total messages: ', len(messages)
message = messages.GetFirst()
#print dir(message)
i=0
while message:
try:
#郵件標題
if hasattr(message,"Subject"):
subject = message.Subject
#郵件接收時間
if hasattr(message,"ReceivedTime"):
received_time = str(message.ReceivedTime)
received_time = datetime.strptime(received_time, "%m/%d/%y %H:%M:%S")
if hasattr(message,"HTMLBody"):
html_body = message.HTMLBody
size = long(message.Size)
#郵件發送人
if hasattr(message,"SenderName"):
sender = message.SenderName
#郵件接收人
if hasattr(message,"To"):
receiver = message.To
#郵件抄送人
if hasattr(message,"Cc"):
cc = message.Cc
#郵件正文
if hasattr(message,"Body"):
body = message.Body
#將郵件內容逐條插入outlook表中,? 為占位符
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()
#獲取下條郵件內容
message = messages.GetNext()
i+=1
print i,subject
except Exception as e:
print "error1:",e
break
except Exception as e:
print "error2:",e
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);
'''

參考地址:

https://msdn.microsoft.com/en-us/library/office/aa155717(v=office.10).aspx

https://www.laurivan.com/python-and-outlook-an-example/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM