读取邮件内容

先引入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")

花了些时间明白了怎么找邮件folder的名字

我用下面的三行

root_folder = outlook.Folders.Item(1)

for folder in root_folder.Folders:

print (folder.Name)

这样就能得到一个名字表

如果还有sub folder,假设上一级folder叫Inbox,这么改就行,继续加代码可以一级一级找#下去

test = outlook.Folders.Item(1).Folders.Item(2)
messages = test.Items

有必要的话写个循环可以得到邮件标题和内容,我就不写了

邮件标题

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)
# 参数说明: formatting_info=True 保留原excel格式
row = r_xls.sheets()[0].nrows # 获取已有的行数
wb = copy(r_xls) # 将xlrd的对象转化为xlwt的对象
table = wb.get_sheet(0) # 获取要操作的sheet

对excel表追加一行内容

    datastyle = xlwt.XFStyle()
    datastyle.num_format_str = 'yyyy-mm-dd'

    table.write(row, 0, a) #括号内分别为行数、列数、内容
    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

你可能感兴趣的:(读取邮件内容)