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

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

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

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

通过使用上述 Python MSG 到 PDF 转换应用程序中的步骤,我们将首先使用 MailMessage 类对象从磁盘访问 EML 或 MSG 文件,然后将电子邮件保存到中间的内存流中MHTML 文件格式。在后续步骤中,我们将使用 Document 类对象访问中间 MHTML 文件,最后将使用 Python* 保存方法将 *EML 转换为 PDF。

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

import aspose.email as ae
import aspose.words as aw
import io
# Path to the source EML/MSG
filePath = "C://SampleTestData//"
# Load the license in your application for converting EML to PDF
emltoPdfLicense = ae.License()
emltoPdfLicense.set_license(filePath + "Conholdate.Total.Product.Family.lic")
# Set the Aspose.Words API license to convert MHTML to PDF
mhtmlToPDFLicense = aw.License()
mhtmlToPDFLicense.set_license(filePath + "Conholdate.Total.Product.Family.lic")
# Access the source EML or MSG file from the disk
srcEmlMessage = ae.MailMessage.load(filePath + "Message.msg")
# Save the email file to a memory stream as an MHTML with default options
int_mhtml_Stream = io.BytesIO()
# Save the EML or MSG file to a stream in MHTML file format
srcEmlMessage.save(int_mhtml_Stream, ae.SaveOptions.default_mhtml)
# Seek the memory position to 0th index
int_mhtml_Stream.seek(0)
# Use the LoadOptions to set the load format to Mhtml
mhtmlLoadOptions = aw.loading.LoadOptions()
mhtmlLoadOptions.load_format = aw.LoadFormat.MHTML
# Create an instance of the Document class to load the MTHML file from Memory Stream
mhtmlDocument = aw.Document(int_mhtml_Stream, mhtmlLoadOptions)
# Close the MHTML Memory Stream
int_mhtml_Stream.close()
# Initialize the PdfSaveOptions class object to se the PDF options
pdfSaveOptions = aw.saving.PdfSaveOptions()
# Save the loaded MHTML file to a PDF using Python
mhtmlDocument.save(filePath + "SaveEmailAsPDF.pdf", pdfSaveOptions)
print ("EML converted to PDF file")

上面的示例展示了为了将 EML 转换为 PDF Python 在简单的 API 调用和定义明确的过程的帮助下使用。此示例可用于 EML 和 MSG 文件格式的电子邮件文件。您还可以通过设置合规性、ColorMode、JpegQuality 和 ImageCompression 等属性来自定义输出 PDF。

本文探讨了将 MSG 转换为 PDF 基于 Python* 的 API。如果您希望在 Python 中拆分 PST 文件,请参阅 如何使用 Python 拆分 PST 文件 上的文章。

 简体中文