1

我目前正在使用 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),这就是我连接上面的“名称”的原因。

4

0 回答 0