【发布时间】:2020-03-09 14:13:58
【问题描述】:
我正在制作一个脚本,用于从 Outlook 保存的消息(.msg 扩展名)中提取特定数据(主题、日期、发件人),并且我想一次将数据填充到 csv 文件中。
所以脚本应该遍历文件夹的带有 msg 扩展名的文件并提取数据。这是我迄今为止能想到的。
此代码创建了初始文件,但它从第一封阅读的电子邮件中复制了 X 次相同的数据,而不是移动到下一封。
import os
import glob
import csv
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
files = glob.glob('PATH_TO_FILES\\*.msg')
for file in files:
msg = outlook.OpenSharedItem(file)
#print(file)
#with open(file) as f:
#msg=f.read()
#print(msg)
with open(r'Email.csv', mode='w') as file:
fieldnames = ['Subject', 'Date', 'Sender']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
#for f in os.listdir('.'):
for f in files:
#if not f.endswith('.msg'):
#continue
#msg = msg.Message(f)
msg_sender = msg.SenderName
msg_date = msg.SentOn
msg_subj = msg.Subject
#msg_message = msg.Body
writer.writerow({'Subject': msg_subj, 'Date': msg_date, 'Sender': msg_sender})
【问题讨论】: