鉴于周报都要读取不同邮件内容,想定时运行便于操作。
import re
from win32com.client.gencache import EnsureDispatch as Dispatch
import pandas as pd
import datetime
def draw_content(my_account,target_receiver):
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI") #构建实例
inbox = outlook.Folders[my_account].Folders["收件箱"] #提取收件箱
Mail_Messages = inbox.Items #提取内容
Mail_Messages.Sort("[ReceivedTime]", True) #按照接受日期排序
for mail in Mail_Messages: #每个邮件进行遍历筛选
if hasattr(mail, 'SenderName'): # 如果有邮件sendername
if mail.SenderName == target_receiver and mail.ReceivedTime.date()>\
(datetime.datetime.now()-datetime.timedelta(days=4)).date()\
and '一对一' in mail.Subject: # 提取收件人,收件时间,收件主题
content = mail.Body
# 原始邮件是表格,读出来是字符串,用正则匹配
a = content.replace('\t','')
test = re.compile(r'总计(.*?)发行')
c = test.findall(content,re.S)
print('ok')
df = pd.DataFrame.from_dict(zip(['申购','赎回','总计'],c[0]))
break
return df
一些相关性质记录:
if (hasattr(mail, 'SenderName')):# 有发件人True, 无正文内容False
SenderName_1 = mail.SenderName
if (hasattr(mail, 'Body')) :#有正文内容True, 无正文内容False
Subject_1 = mail.Subject
if (hasattr(mail, 'CC')): # 抄送人
cc_cc_1 = mail.CC
if (hasattr(mail, 'Attachments')): # 抄送人
con = mail.Attachments.Item(1) #从1开始
写邮件:
import win32com.client as win32
outlook = win32.Dispatch('Outlook.Application')
mail_item = outlook.CreateItem(0) # 0: creat mail
mail_item.Recipients.Add('xx@phfund.com.cn')
mail_item.Subject = 'Mail Test'
mail_item.BodyFormat = 2 # 2: Html format
mail_item.HTMLBody = '''
<H2>Hello, This is a test mail.</H2>
Hello Guys.
'''
mail_item.Attachments.Add('C:\\Users\\xx\\Desktop\\慢慢慢.txt')
mail_item.Send()
尚存问题:
- 原始邮件是表格,读出来缺失字符串,用正则尚未匹配成功,仍需尝试。
2.附件没法直接读取,要保存后再读取,尚需探索。
网友评论