目的:用python下载收件箱内指定发件人的邮件附件后读取,但总是报错:(
from win32com.client.gencache import EnsureDispatch as Dispatch
import pandas as pd
import datetime
from bs4 import BeautifulSoup
import os
#import poplib
__author__ = 'Evan'
def read_outlook_mailbox():
"""连接Outlook邮箱,读取收件箱内的邮件内容"""
# 使用MAPI协议连接Outlook
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
# 获取收件箱所在位置
inbox = outlook.Folders[""].Folders["收件箱"]
# 获取收件箱下的所有邮件
Mail_Messages = inbox.Items # 提取内容
Mail_Messages.Sort("[ReceivedTime]", True) # 按照接受日期排序
a = Mail_Messages.Restrict("[SenderName]=''")
a = a.Restrict("[ReceivedTime]='1/28/2022'")
Highrisk_BP=pd.DataFrame(columns=['邮件主题','邮件时间'])
print(len(a))
i = 0
def mail():
global mail
for mail in a:
if (('招行,工行到款,请认款,另附KAB格式,以便查询' in mail.Subject)):
print('接收时间:{}'.format(str(mail.ReceivedTime)[0:10]))
Highrisk_BP.loc[i, '邮件时间'] = str(mail.ReceivedTime)[0:10]
print(type(mail.ReceivedTime))
print('主题:{}'.format(mail.Subject))
Highrisk_BP.loc[i, '邮件主题'] = mail.Subject
print('邮件附件数量:{}'.format(mail.Attachments.Count))
i += 1
Highrisk_BP.to_excel('D:\\email\\Highrisk_BP2020.xlsx')
# 保存邮件中的附件,如果没有附件不会执行也不会产生异常
attachment = mail.Attachments
for each in attachment:
save_attachment_path = 'D:\\email\\attachment' # 保存附件到当前路径
each.SaveAsFile(r'{}\{}'.format(save_attachment_path, each.FileName))
print('附件({})保存完毕'.format(each.FileName))
read_outlook_mailbox()
可能文件名和方法名重名了,检查之后修改即可。
以上仅供参考,如有任何疑问,可以评论回复,看到即回,希望对题主有所帮助!