加载、保存和转换电子邮件

检测电子邮件文件格式

Aspose.Email API 提供了检测提供的邮件文件格式的能力。 DetectFileFormat 方法的 FileFormatUtil 可以使用该类来实现此功能。以下类和方法可用于检测已加载的文件格式:

下面的代码片段展示了如何检测文件格式:

from aspose.email.tools import FileFormatUtil

# Detect file format and get the detected load format
info = FileFormatUtil.detect_file_format(data_dir + "message.msg")
print("The message format is: " + str(info.file_format_type))

使用加载选项加载消息

下面的代码片段展示了如何使用加载选项加载消息。

from aspose.email import MailMessage, EmlLoadOptions, HtmlLoadOptions, MhtmlLoadOptions, MsgLoadOptions

# Load Eml, html, mhtml, msg, and dat files
mail_message = MailMessage.load(data_dir + "message.eml", EmlLoadOptions())
MailMessage.load(data_dir + "description.html", HtmlLoadOptions())
MailMessage.load(data_dir + "message.mhtml", MhtmlLoadOptions())
MailMessage.load(data_dir + "message.msg", MsgLoadOptions())

# Loading with custom options
eml_load_options = EmlLoadOptions()
eml_load_options.preferred_text_encoding = "utf-8"
eml_load_options.preserve_tnef_attachments = True

MailMessage.load(data_dir + "description.html", eml_load_options)

html_load_options = HtmlLoadOptions()
html_load_options.preferred_text_encoding = "utf-8"
html_load_options.should_add_plain_text_view = True
html_load_options.path_to_resources = data_dir

MailMessage.load(data_dir + "description.html", html_load_options)

加载时保留嵌入的消息格式

from aspose.email import MailMessage, EmlLoadOptions, HtmlLoadOptions, MhtmlLoadOptions, MsgLoadOptions
from aspose.email.tools import FileFormatUtil

eml_load_options = EmlLoadOptions()
eml_load_options.preserve_embedded_message_format = True

mail = MailMessage.load(data_dir + "message.eml", eml_load_options)

file_format = FileFormatUtil.detect_file_format(mail.attachments[0].content_stream).file_format_type

print("Embedded message file format: " + str(file_format))

保存和转换电子邮件

Aspose.Email 让将任何消息类型转换为其他格式变得轻松。为演示此功能,本文的代码从磁盘加载三种类型的消息并将它们保存为其他格式。基类 SaveOptions 以及这些类 EmlSaveOptions, MsgSaveOptions, MhtSaveOptions, HtmlSaveOptions 可用于在将消息保存为其他格式时进行额外设置。本文展示了如何使用这些类将示例电子邮件保存为:

  • EML 格式。
  • Outlook MSG。
  • MHTML 格式。
  • HTML 格式。

另存为 EML

下面的代码片段展示了如何加载 EML 消息并以相同格式保存到磁盘。

from aspose.email import MailMessage, SaveOptions

# Initialize and Load an existing EML file by specifying the MessageFormat
mail_message = MailMessage.load(data_dir + "message.eml")

mail_message.save(data_dir + "LoadAndSaveFileAsEML_out.eml", SaveOptions.default_eml)

在 EML 文件中保留边界

下面的代码片段展示了如何加载 EML 文件并以相同格式保存,同时保留原始边界。

from aspose.email import MailMessage, EmlSaveOptions, MailMessageSaveType

mail_message = MailMessage.load(data_dir + "message.eml")

# Save as eml with preserved original boundaries
eml_save_options = EmlSaveOptions(MailMessageSaveType.eml_format)

mail_message.save(data_dir + "PreserveOriginalBoundaries_out.eml", eml_save_options)

自定义 MIME 边界字符串

Aspose.Email for .NET 允许您配置 MIME 消息中使用的边界模板。这通过 boundaries_template 属性的 EmlSaveOptions 类。

通过设置自定义模板,您可以定义 MIME 边界的生成方式。模板中的 {#} 通配符将被替换为递增的边界编号,从而实现动态且可读的边界字符串。

如果 boundaries_template 如果未设置(默认为 None),库将使用内部的边界格式。

下面的代码示例展示了在将电子邮件保存为 .eml 格式时如何自定义 MIME 边界字符串:

import aspose.email as ae

# Create a sample MailMessage
message = ae.MailMessage()
message.subject = "Custom MIME Boundary"
message.body = "This message uses a custom MIME boundary template."
message.to.append(ae.MailAddress("recipient@example.com"))

# Configure save options with a custom boundary template
save_options = ae.EmlSaveOptions(ae.MailMessageSaveType.EML_FORMAT)
save_options.boundaries_template = "boundary--{#}"

# Save the message to .eml with custom boundaries
message.save("Custom_Boundary_Message.eml", save_options)

以下是使用上述代码保存的自定义边界的消息结构示例

From: sender@example.com  
To: recipient@example.com  
Subject: Custom_Boundary_Message  
Date: Fri, 27 Dec 2024 12:00:00 +0000
Content-Type: multipart/mixed;
 boundary="boundary--1"

This is a multi-part message in MIME format.

--boundary--1
Content-Type: multipart/alternative; boundary="boundary--2"


--boundary--2
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: quoted-printable

Content-Type: text/plain; charset="us-ascii"

This is the plain text content of the email.


--boundary--2
Content-Type: text/html; charset="windows-1251"
Content-Transfer-Encoding: quoted-printable

<html>
  <body>
    <p>This is the <b>HTML</b> content of the email.</p>
  </body>
</html>

--boundary--2--

--boundary--1
Content-Type: application/octet-stream; name="report-2023-08.xlsx"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="report-2023-08.xlsx"

UEsDBBQABgAIAAAAIQBi7...

--boundary--1--

在 EML 文件中保留 TNEF 附件

下面的代码片段展示了如何在保存 EML 文件时保留 TNEF 附件。

from aspose.email import MailMessage, EmlSaveOptions, MailMessageSaveType, FileCompatibilityMode

mail_message = MailMessage.load(data_dir + "message.eml")

# Save as eml with preserved attachment
eml_save_options = EmlSaveOptions(MailMessageSaveType.eml_format)
eml_save_options.file_compatibility_mode = FileCompatibilityMode.PRESERVE_TNEF_ATTACHMENTS

mail_message.save(data_dir + "PreserveTNEFAttachment_out.eml", eml_save_options)

另存为 MSG

下面的代码片段展示了如何加载 EML 消息并使用 SaveOptions.

from aspose.email import MailMessage, SaveOptions, MailMessageSaveType, FileCompatibilityMode

# Initialize and Load an existing EML file by specifying the MessageFormat
eml = MailMessage.load(data_dir + "message.eml")

# Save the Email message to disk in ASCII format and Unicode format
eml.save(data_dir + "AnEmail_out.msg", SaveOptions.default_msg_unicode)

在 MSG 文件中保留日期

MsgSaveOptions class 允许将源消息另存为 Outlook Message 文件(MSG),并保留日期。下面的代码片段展示了如何将 EML 文件另存为 MSG 并保留日期。

from aspose.email import MailMessage, MsgSaveOptions, MailMessageSaveType, FileCompatibilityMode

# Initialize and Load an existing EML file by specifying the MessageFormat
eml = MailMessage.load(data_dir + "message.eml")

# Save as msg with preserved dates
msg_save_options = MsgSaveOptions(MailMessageSaveType.outlook_message_format_unicode)
msg_save_options.preserve_original_dates = True

eml.save(data_dir + "outTest_out.msg", msg_save_options)

另存为 MHTML

可以使用不同的 MHTML 选项来获得期望的结果。以下代码片段展示了如何将 EML 消息加载到 MailMessage 并将其转换为 MHTML。

from aspose.email import MailMessage, SaveOptions, MailMessageSaveType, FileCompatibilityMode

# Initialize and Load an existing EML file by specifying the MessageFormat
eml = MailMessage.load(data_dir + "message.eml")

eml.save(data_dir + "AnEmail_out.mhtml", SaveOptions.default_mhtml)

自定义 MHTML 转换设置

MhtSaveOptions 该类提供将电子邮件消息保存为 MHTML 格式的额外选项。枚举 MhtFormatOptions 使得可以将额外的电子邮件信息写入输出 MHTML。可以写入以下附加字段:

  • NONE - 未指定特定设置。
  • WRITE_HEADER - 表示应写入头部信息。
  • WRITE_OUTLINE_ATTACHMENTS - 表示应写入大纲附件。
  • WRITE_COMPLETE_EMAIL_ADDRESS - 表示应在所有电子邮件头部中写入完整的电子邮件地址。
  • NO_ENCODE_CHARACTERS - 表示不应使用字符的传输编码。
  • HIDE_EXTRA_PRINT_HEADER - 表示 PageHeader 将不可见。
  • WRITE_COMPLETE_TO_EMAIL_ADDRESS - 表示应在 ‘To’ 头部中写入完整的电子邮件地址。
  • WRITE_COMPLETE_FROM_EMAIL_ADDRESS - 表示应在 ‘From’ 头部中写入完整的电子邮件地址。
  • WRITE_COMPLETE_CC_EMAIL_ADDRESS - 表示应在 ‘Cc’ 头部中写入完整的电子邮件地址。
  • WRITE_COMPLETE_BCC_EMAIL_ADDRESS - 表示应在 ‘Bcc’ 头部中写入完整的电子邮件地址。
  • RENDER_CALENDAR_EVENT - 表示应在输出 mhtml 中写入日历事件的文本。
  • SKIP_BYTE_ORDER_MARK_IN_BODY - 表示应将字节顺序标记(BOM)写入正文。
  • RENDER_V_CARD_INFO - 表示应在输出 mhtml 中写入 VCard AlternativeView 的文本。
  • DISPLAY_AS_OUTLOOK - 表示 From 头部将在输出中按 Outlook 的显示方式呈现。
  • RENDER_TASK_FIELDS - 表示应在输出 mhtml 中写入特定的任务字段。

下面的代码片段展示了如何使用可选设置将 EML 文件转换为 MHTML。

from aspose.email import MailMessage, MhtSaveOptions, MhtFormatOptions, MailMessageSaveType, FileCompatibilityMode

# Load an existing EML file
eml = MailMessage.load(data_dir + "message.eml")

# Save as mht with header
mht_save_options = MhtSaveOptions()

# Specify formatting options required
# Here we are specifying to write header information to output without writing extra print header
# and the output headers should be displayed as the original headers in the message
mht_save_options.mht_format_options = MhtFormatOptions.WRITE_HEADER | MhtFormatOptions.HIDE_EXTRA_PRINT_HEADER | MhtFormatOptions.DISPLAY_AS_OUTLOOK

# Check the body encoding for validity.
mht_save_options.check_body_content_encoding = True

eml.save(data_dir + "outMessage_out.mht", mht_save_options)

在 MHTML 转换中包含日历事件

MhtFormatOptions.RenderCalendarEvent 将日历事件渲染到输出的 MHTML。下面的代码片段展示了在转换为 MHTML 时如何渲染日历事件:

from aspose.email import MailMessage, MhtSaveOptions, MhtFormatOptions, MhtTemplateName, MailMessageSaveType, FileCompatibilityMode

file_name = "message.msg"

# Load the MSG file
msg = MailMessage.load(data_dir + file_name)

# Create MHT save options
options = MhtSaveOptions()
options.mht_format_options = MhtFormatOptions.WRITE_HEADER | MhtFormatOptions.RENDER_CALENDAR_EVENT

# Save the message as MHTML
msg.save(data_dir + "Meeting with Recurring Occurrences.mhtml", options)

导出为不含内联图片的 MHT

from aspose.email import MailMessage, MhtSaveOptions, MhtFormatOptions, MhtTemplateName, MailMessageSaveType, FileCompatibilityMode

# Load the EML file
eml = MailMessage.load(data_dir + "message.eml")

# Create MHT save options
mht_save_options = MhtSaveOptions()
mht_save_options.skip_inline_images = True

# Save the message as MHTML without inline images
eml.save(data_dir + "EmlToMhtmlWithoutInlineImages_out.mht", mht_save_options)

使用自定义时区导出电子邮件为 MHT

MailMessage class 提供了 TimeZoneOffset 属性用于在导出为 MHT 时设置自定义时区。下面的代码片段展示了如何使用自定义时区将电子邮件导出为 MHT:

from aspose.email import MailMessage, MhtSaveOptions, MhtFormatOptions, MhtTemplateName, MailMessageSaveType, FileCompatibilityMode
from datetime import timedelta

# Load the EML file
eml = MailMessage.load(data_dir + "message.eml")

# Set the local time for message date
eml.time_zone_offset = timedelta(hours=-8)

# The dates will be rendered by the local system time zone
mht_save_options = MhtSaveOptions()
mht_save_options.mht_format_options = MhtFormatOptions.WRITE_HEADER
eml.save(data_dir + "ExportEmailToMHTWithCustomTimezone_out.mhtml", mht_save_options)

另存为 HTML

HtmlSaveOptions class 允许将消息正文导出为 HTML,并可选择保存嵌入资源。下面的代码片段展示了如何将消息另存为 HTML,其中 embed_resources 的默认值为 true。

from aspose.email import MailMessage, SaveOptions, HtmlSaveOptions, HtmlFormatOptions

# Load the EML file
message = MailMessage.load(data_dir + "message.eml")

# Save the Email message as HTML
message.save(data_dir + "SaveAsHTML_out.html", SaveOptions.default_html)

# OR

eml = MailMessage.load(data_dir + "message.eml")
options = HtmlSaveOptions()
options.embed_resources = False
options.html_format_options = (
    HtmlFormatOptions.WRITE_HEADER
    | HtmlFormatOptions.WRITE_COMPLETE_EMAIL_ADDRESS
)  # save the message headers to output HTML using the formatting options
eml.save(data_dir + "SaveAsHTML1_out.html", options)

另存为 Outlook 模板(.OFT)

下面的代码片段展示了如何将消息另存为 Outlook 模板(.oft)文件。

from aspose.email import MailMessage, SaveOptions

eml = MailMessage("test@from.to", "test@to.to", "template subject", "Template body")

oft_eml_file_name = "EmlAsOft_out.oft"
options = SaveOptions.default_msg_unicode
options.save_as_template = True
eml.save(data_dir + oft_eml_file_name, options)