先引入outlook
-- coding:utf-8 --
import win32com.client
import time
from datetime import datetime as dt
from datetime import timedelta,timezone
import os
import pytz
import linecache
import pandas as pd
from xlrd import open_workbook
from xlutils.copy import copy
import xlwt
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
花了些時(shí)間明白了怎么找郵件folder的名字
我用下面的三行
root_folder = outlook.Folders.Item(1)
for folder in root_folder.Folders:
print (folder.Name)
這樣就能得到一個(gè)名字表
如果還有sub folder啃炸,假設(shè)上一級(jí)folder叫Inbox裹唆,這么改就行,繼續(xù)加代碼可以一級(jí)一級(jí)找#下去
test = outlook.Folders.Item(1).Folders.Item(2)
messages = test.Items
有必要的話寫個(gè)循環(huán)可以得到郵件標(biāo)題和內(nèi)容阔墩,我就不寫了
郵件標(biāo)題
utc=pytz.UTC
path = "D:\OWS\Python\python_test\email_attachment\"
for m in messages:
wdate=dt.strftime(dt.now(),"%Y-%m-%d")
bdate=dt.strftime(dt.now()-timedelta(days=1),"%Y-%m-%d")
timecap= dt.now().replace(tzinfo=utc)-m.ReceivedTime.replace(tzinfo=utc)
cap = timecap>timedelta(hours=24)
Rdate=dt.strftime(m.ReceivedTime,"%Y-%m-%d")
if 'Leaving Indonesia' in m.Subject: #and cap ==False :
#print(timecap)
#print(timecap>timedelta(hours=24))
#print("subject: ", m.Subject)
#print(m.ReceivedTime)
#print(Rdate)
#print(m.sender)
with open(path+"emailbody.txt", "w+", encoding='utf-8') as f:
f.write(m.body)
with open(path+"emailbody.txt", "r+", encoding='utf-8') as f:
lines = f.readlines()
for num , line in enumerate(lines,1):
line = line.strip()
if line == "NAME":
#print(num)
break
else:
continue
a=linecache.getline(path+"emailbody.txt", num+20).strip()
b=linecache.getline(path+"emailbody.txt", num+24).strip()
c=linecache.getline(path+"emailbody.txt", num+28).strip()
d=linecache.getline(path+"emailbody.txt", num+32).strip()
e=linecache.getline(path+"emailbody.txt", num+36).strip()
alist=[a,b,c,d,e,wdate]
#print(alist)
r_xls = open_workbook(path+bdate+".xls") # 讀取excel文件
#rb = open_workbook(path+"IRO-leavingIndonesiaReport.xls",formatting_info=True)
# 參數(shù)說明: formatting_info=True 保留原excel格式
row = r_xls.sheets()[0].nrows # 獲取已有的行數(shù)
wb = copy(r_xls) # 將xlrd的對(duì)象轉(zhuǎn)化為xlwt的對(duì)象
table = wb.get_sheet(0) # 獲取要操作的sheet
對(duì)excel表追加一行內(nèi)容
datastyle = xlwt.XFStyle()
datastyle.num_format_str = 'yyyy-mm-dd'
table.write(row, 0, a) #括號(hào)內(nèi)分別為行數(shù)镜豹、列數(shù)侵蒙、內(nèi)容
table.write(row, 1, b)
table.write(row, 2, c)
table.write(row, 3, d)
table.write(row, 4, e)
table.write(row, 5,Rdate)
#table.write(row, 5, wdate,datastyle)
#os.remove(path+"IRO-leavingIndonesiaReport.xls")
wb.save(path+"IRO-leavingIndonesiaReport.xls") # 保存并覆蓋文件
wb.save(path+wdate+".xls")
else:
continue