使用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/

转载于:https://www.cnblogs.com/skyer/p/6728112.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值