通過python 來實現(xiàn)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):
# 創(chuàng)建與outlook的鏈接
self.outlook= win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
# 獲取outlook的登陸權(quán)限
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()