我目前正在使用Python开发自动化解决方案,以读取传入的Outlook电子邮件并下载所有附件。我正在使用exchangelib库来实现此目的。我能够读取电子邮件正文并能够保存文件附件(.pdf,.jpg,.xlsx),但是面临有关如何下载Outlook项目(.msg附件)的问题。例如:有人提供了电子邮件批准或附件中的电子邮件其他信息等。)。我通读了Exchangelib文档,但没有有关如何保存Outlook附件的任何信息。
我通过改变各种模式“ w”,“ wb”尝试了各种方式,但是没有运气。
我的代码
# Read & Save Attachments code
for item in emails.all().order_by('-datetime_received')[:1]:
for attachment in item.attachments:
print('Number of Attachment found:', len(item.attachments))
if isinstance(attachment, FileAttachment):
local_path=os.path.join('C:/Attachments', attachment.name)
with open(local_path, 'wb') as f, attachment.fp as fp:
buffer = fp.read(1024)
while buffer:
f.write(buffer)
buffer = fp.read(1024)
print('Saved attachment to', local_path)
elif isinstance(attachment, ItemAttachment):
name = str(attachment.name)+'.msg'
local_path=os.path.join('C:/Attachments/', name)
with open(local_path, 'w') as f:
f.write(attachment.item.body)
print('Saved attachment to', local_path)
Exchangelib示例示例
for item in a.inbox.all():
for attachment in item.attachments:
if isinstance(attachment, FileAttachment):
local_path = os.path.join('/tmp', attachment.name)
with open(local_path, 'wb') as f:
f.write(attachment.content)
print('Saved attachment to', local_path)
elif isinstance(attachment, ItemAttachment):
if isinstance(attachment.item, Message):
print(attachment.item.subject, attachment.item.body)
使用上面的代码,我所看到的只是一个使用主题名称创建的文件,但文件名为0 kb(无内容)且没有扩展名(.msg),这就是为什么我要串联上面的“名称”的原因。