通过python 来实现outlook中邮件的保存。
import win32com.client
import os, sys, shutil
OlSaveAsType= {
"olTXT": 0,
"olRTF": 1,
"olTemplate": 2,
"olMSG": 3,
"olDoc": 4,
"olHTML": 5,
"olVCard": 6,
"olVCal": 7,
"olICal": 8
}
class ReadMail(object):
def __init__(self):
# 创建与outlook的链接
self.outlook= win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
# 获取outlook的登陆权限
self.accounts= win32com.client.Dispatch("Outlook.Application").Session.Accounts
self.folders= self.get_folder_name()
#获取邮箱中所有文件的名字
def get_folder_name(self):
for accountin self.accounts:
# 获取邮箱里所有文件的名字
global inbox
inbox= self.outlook.Folders(account.DeliveryStore.DisplayName)
print(account.DisplayName)
self.folders= inbox.Folders
return self.folders
def run(self):
for folderin self.folders:
if folder.name== '你要保存的邮件所在的分组名称':
self.save_report(folder)
else:
pass
#TODO 将最后一封邮件保存到本地
def save_report(self,folder):
# 将之前留下的文件全部清除掉
shutil.rmtree(r'\path\to\you\save\', ignore_errors=True)
# 获取最新的邮件
report= folder.Items.GetLast()
# 将最新的邮件储存到目标目录
os.chdir(r"\path\to\you\save\")
report.SaveAs(report.subject+ ".html", OlSaveAsType['olHTML'])
print(report.subject)
if __name__== '__main__':
savereport= ReadMail()
savereport.run()