在 Python 中刪除 Outlook 電子郵件中的附件

上一篇博文 中,您了解瞭如何在 Outlook 電子郵件中添加或提取附件。但是,在某些情況下,您必須在轉發之前從電子郵件中刪除部分或所有附件。因此,在本文中,您將學習如何使用 Python 從 Outlook 電子郵件中刪除附件。

用於刪除 Outlook 電子郵件附件的 Python 庫

Aspose.Email for Python 是一個功能豐富的庫,用於在 Python 應用程序中創建和發送電子郵件。使用該庫,您還可以處理 Outlook 電子郵件並操縱其內容。我們將使用此庫刪除 Outlook 電子郵件中的附件。您可以 下載 庫或使用以下命令安裝它。

> pip install Aspose.Email-for-Python-via-NET

使用 Python 刪除 Outlook 電子郵件中的附件

以下是使用 Python 從 Outlook 電子郵件中刪除附件的步驟。

  • 使用 MailMessage.load() 方法加載 Outlook 電子郵件。
  • 使用文件名將所需附件引用到對像中。
  • 調用 MailMessage.attachments.remove(Attachment) 方法移除附件。
  • 最後,使用 MailMessage.save() 方法保存更新的電子郵件。

以下代碼示例展示瞭如何使用 Python 從 Outlook 電子郵件中刪除附件。

from aspose.email import MailMessage
from aspose.email import Attachment
from aspose.email import SaveOptions

dataDir = "Data/"

# 加載電子郵件
message = MailMessage.load(dataDir + "email1.msg")

# 添加附件
attachment = Attachment(dataDir + "1.txt")
message.attachments.append(attachment)

# 打印附件數量
print("Attachments count before removing: " + str(len(message.attachments)))

# 刪除附件
message.attachments.remove(attachment)

# 保存更新的 Outlook 電子郵件
message.save(dataDir + "updated.msg", SaveOptions.default_msg_unicode)

# 打印附件數量 after removal
print("Attachments count after removing: " + str(len(message.attachments)))

# 保存更新的 Outlook 電子郵件
message.save(dataDir + "updated.msg", SaveOptions.default_msg_unicode)

在 Python 中刪除所有 Outlook 電子郵件附件

Aspose.Email for Python 還提供了一種一次性從電子郵件中刪除所有附件的方法。為此,使用了 MapiMessage.DestroyAttachments() 方法。以下代碼示例展示瞭如何使用 Python 刪除 Outlook 電子郵件中的所有附件。

from aspose.email.mapi import MapiMessage

dataDir = "Data/"

# 從電子郵件中刪除所有附件
MapiMessage.destroy_attachments(dataDir + "email1.msg")

用於刪除 Outlook 電子郵件附件的 Python 庫 - 獲取免費許可證

您可以使用免費的臨時許可證 不受評估限制地從 MS Outlook 電子郵件中刪除附件。

結論

在本文中,您學習瞭如何使用 Python 從 Outlook 電子郵件中刪除附件。我們已經明確介紹瞭如何從 Outlook 電子郵件中一次刪除特定附件或所有附件。

Aspose 的 Python Outlook 庫 - 閱讀更多

您可以使用 文檔 探索更多關於 Aspose 的 Outlook 庫。另外,從 GitHub 下載完整的源代碼示例包。此外,您可以在我們的 論壇 上發布您的問題。

也可以看看