如何使用 Python 将 Outlook 电子邮件转换为 Word

在这个简单的教程中,我们将学习如何使用 Python Outlook Email 转换为 Word 以及配置环境的详细步骤。您将观察到,为了将 EML 转换为 DOCX,可以使用基于 Python 的 API,并且您可以在任何常用操作系统(如 Windows 或 Linux)中使用此示例。

使用 Python 将 Outlook 电子邮件转换为 DOCX 的步骤

  1. 在您的应用程序中将环境设置为 通过 .NET 使用 Aspose.Email for PythonAspose.Words for Python 通过 .NET 以在 Python 中将电子邮件转换为 Word
  2. 创建 MailMessage 类对象以从磁盘或邮件服务器加载源 MSG 或 EML 文件
  3. 将加载的电子邮件 (EML/MSG) 文件以 MHTML 格式导出到内存流
  4. 将 LoadFormat 初始化为 MHTML 并创建 Document 类的实例以加载中间 MHTML 文件
  5. 通过使用 Python 中的 save 方法执行 EML 到 Word 的转换

按照前面提到的 Python 电子邮件到 Word 转换应用程序中的步骤,我们将首先使用 MailMessage 类的实例从磁盘加载源 EML 或 MSG 文件,然后将加载的电子邮件文件保存到MHTML 格式的内存流。最后,中间 MHTML 将使用 Document 类的实例从内存流中加载,以将电子邮件转换为 DOCX。

使用 Python 将 Outlook 电子邮件转换为 DOCX 的代码

import aspose.email as ae
import aspose.words as aw
import io
# Path to the source files
filePath = "Y://SampleData//"
# Load the license in your application for converting EML to MHTML
emlLicense = ae.License()
emlLicense.set_license(filePath + "Conholdate.Total.Product.Family.lic")
# Set the Aspose.Words license for converting MHTML to a DOCX file
wordsLicense = aw.License()
wordsLicense.set_license(filePath + "Conholdate.Total.Product.Family.lic")
# Load the source EML or MSG file from the disk or mail server
srcMessage = ae.MailMessage.load(filePath + "Message.msg")
# Save email to stream as a MHTML with default options
mhtml_Stream = io.BytesIO()
# Save the email to MHTML file to a memory stream
srcMessage.save(mhtml_Stream, ae.SaveOptions.default_mhtml)
# Reset the Memory stream position
mhtml_Stream.seek(0)
# Configure the LoadOptions to set the load format to Mhtml
loadOptions = aw.loading.LoadOptions()
loadOptions.load_format = aw.LoadFormat.MHTML
# Instantiate the Document class object to load the intermediate MTHML from MemoryStream
mhtmlDocument = aw.Document(mhtml_Stream, loadOptions)
# Close the MHTML stream now
mhtml_Stream.close()
# Save the loaded MHTML to DOCX in Python
mhtmlDocument.save(filePath + "SaveEmailAsDoc.docx")
print ("EML converted to Word file")

在上面的示例中,为了将 EML 转换为 Word,Python* 借助简单的 API 接口和明确定义的步骤使用。上述代码可用于 MSG 或 EML 格式的电子邮件文件。您也可以将加载的 MHTML 导出为图像或 PDF 文件格式。

在本主题中,我们学习了如何使用基于 Python* 的 API *将 Outlook 电子邮件转换为 Docx。如果您希望将 MBOX 文件转换为 PST 文件,请参阅 如何在 Python 中将 MBOX 转换为 PST 文件 上的文章。

 简体中文