Tải, lưu và chuyển đổi email
Phát hiện định dạng tệp Email
API Aspose.Email cung cấp khả năng phát hiện định dạng tệp của tệp tin tin nhắn được cung cấp. The DetectFileFormat phương thức của FileFormatUtil Lớp có thể được sử dụng để đạt được điều này. Các lớp và phương thức sau có thể được sử dụng để phát hiện định dạng tệp đã tải:
- Enum FileFormatType
- Lớp FileFormatInfo
- Lớp FileFormatUtil
- Phương thức detect_file_format(stream)
- Phương thức detect_file_format(file_path)
Đoạn mã dưới đây cho bạn thấy cách phát hiện các định dạng tệp:
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))
Tải tin nhắn với các tùy chọn tải
Đoạn mã dưới đây cho bạn thấy cách tải một tin nhắn với các tùy chọn tải.
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)
Giữ định dạng tin nhắn nhúng khi tải
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))
Lưu và chuyển đổi email
Aspose.Email giúp dễ dàng chuyển đổi bất kỳ loại tin nhắn nào sang định dạng khác. Để minh họa tính năng này, mã trong bài viết này tải ba loại tin nhắn từ đĩa và lưu chúng lại ở các định dạng khác. Lớp cơ sở SaveOptions và các lớp EmlSaveOptions, MsgSaveOptions, MhtSaveOptions, HtmlSaveOptions có thể được sử dụng cho các cài đặt bổ sung khi lưu tin nhắn sang các định dạng khác. Bài viết chỉ ra cách sử dụng các lớp này để lưu một email mẫu dưới dạng:
- Định dạng EML.
- Outlook MSG.
- Định dạng MHTML.
- Định dạng HTML.
Lưu dưới dạng EML
Đoạn mã dưới đây cho bạn thấy cách tải một tin nhắn EML và lưu nó vào đĩa ở cùng định dạng.
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)
Giữ ranh giới trong tệp EML
Đoạn mã dưới đây cho bạn thấy cách tải tệp EML và lưu lại ở cùng định dạng, giữ nguyên các ranh giới gốc.
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)
Tùy chỉnh chuỗi ranh giới MIME
Aspose.Email cho .NET cho phép bạn cấu hình mẫu ranh giới được sử dụng trong các tin nhắn MIME. Điều này được thực hiện thông qua boundaries_template thuộc tính của EmlSaveOptions lớp.
Bằng cách thiết lập một mẫu tùy chỉnh, bạn có thể định nghĩa cách các ranh giới MIME được tạo. Ký tự đại diện {#} trong mẫu sẽ được thay thế bằng một số ranh giới tăng dần, cho phép các chuỗi ranh giới động và dễ đọc.
Nếu boundaries_template không được đặt (mặc định là None), thư viện sẽ sử dụng định dạng ranh giới nội bộ.
Mẫu mã dưới đây cho thấy cách tùy chỉnh chuỗi ranh giới MIME khi lưu một tin nhắn email dưới định dạng .eml:
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)
Đây là một ví dụ về cấu trúc tin nhắn với các ranh giới tùy chỉnh được lưu bằng mã ở trên:
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--
Giữ tệp đính kèm TNEF trong tệp EML
Đoạn mã dưới đây cho bạn thấy cách lưu tệp EML mà vẫn giữ các tệp đính kèm 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)
Lưu dưới dạng MSG
Đoạn mã dưới đây cho bạn thấy cách tải một tin nhắn EML và chuyển đổi nó sang MSG bằng tùy chọn thích hợp từ 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)
Giữ ngày tháng trong tệp MSG
Cái MsgSaveOptions class cho phép bạn lưu tin nhắn nguồn dưới dạng tệp Outlook Message (MSG) giữ nguyên ngày tháng. Đoạn mã dưới đây cho bạn thấy cách lưu tệp EML dưới dạng MSG và giữ ngày tháng.
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)
Lưu dưới dạng MHTML
Các tùy chọn khác nhau của MHTML có thể được sử dụng để đạt được kết quả mong muốn. Đoạn mã dưới đây cho bạn cách tải một tin nhắn EML vào MailMessage và chuyển đổi nó sang 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)
Cài đặt chuyển đổi MHTML tùy chỉnh
Cái MhtSaveOptions lớp cung cấp các tùy chọn bổ sung để lưu các tin nhắn email ở định dạng MHTML. Bộ liệt kê MhtFormatOptions cho phép ghi thêm thông tin email vào MHTML đầu ra. Các trường bổ sung sau có thể được ghi:
- NONE - Không có cài đặt nào được chỉ định.
- WRITE_HEADER - Cho biết thông tin tiêu đề sẽ được ghi.
- WRITE_OUTLINE_ATTACHMENTS - Cho biết các tệp đính kèm outline sẽ được ghi.
- WRITE_COMPLETE_EMAIL_ADDRESS - Cho biết địa chỉ email đầy đủ sẽ được ghi trong tất cả các tiêu đề email.
- NO_ENCODE_CHARACTERS - Cho biết không sử dụng mã hóa truyền ký tự nào.
- HIDE_EXTRA_PRINT_HEADER - Cho biết PageHeader sẽ không hiển thị.
- WRITE_COMPLETE_TO_EMAIL_ADDRESS - Cho biết địa chỉ email đầy đủ sẽ được ghi trong tiêu đề ‘To’.
- WRITE_COMPLETE_FROM_EMAIL_ADDRESS - Cho biết địa chỉ email đầy đủ sẽ được ghi trong tiêu đề ‘From’.
- WRITE_COMPLETE_CC_EMAIL_ADDRESS - Cho biết địa chỉ email đầy đủ sẽ được ghi trong tiêu đề ‘Cc’.
- WRITE_COMPLETE_BCC_EMAIL_ADDRESS - Cho biết địa chỉ email đầy đủ sẽ được ghi trong tiêu đề ‘Bcc’.
- RENDER_CALENDAR_EVENT - Cho biết văn bản từ sự kiện lịch sẽ được ghi trong mhtml đầu ra.
- SKIP_BYTE_ORDER_MARK_IN_BODY - Cho biết các byte Byte Order Mark (BOM) sẽ được ghi vào phần thân.
- RENDER_V_CARD_INFO - Cho biết văn bản từ VCard AlternativeView sẽ được ghi trong mhtml đầu ra.
- DISPLAY_AS_OUTLOOK - Cho biết tiêu đề From sẽ được hiển thị như trong Outlook.
- RENDER_TASK_FIELDS - Cho biết các trường Task cụ thể sẽ được ghi trong mhtml đầu ra.
Đoạn mã dưới đây cho bạn thấy cách chuyển đổi tệp EML sang MHTML với các cài đặt tùy chọn.
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)
Bao gồm sự kiện Lịch trong chuyển đổi MHTML
Cái MhtFormatOptions.RenderCalendarEvent kết xuất các sự kiện Lịch vào MHTML đầu ra. Đoạn mã dưới đây cho bạn thấy cách kết xuất các sự kiện lịch khi chuyển đổi sang 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)
Xuất email sang MHT mà không có hình ảnh nhúng
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)
Xuất email sang MHT với múi giờ tùy chỉnh
MailMessage class cung cấp TimeZoneOffset thuộc tính để đặt múi giờ tùy chỉnh khi xuất sang MHT. Đoạn mã dưới đây cho bạn thấy cách xuất một email sang MHT với múi giờ tùy chỉnh:
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)
Lưu dưới dạng HTML
Cái HtmlSaveOptions class cho phép bạn xuất phần thân tin nhắn ra HTML với tùy chọn lưu các tài nguyên nhúng. Đoạn mã dưới đây cho bạn thấy cách lưu một tin nhắn dưới dạng HTML trong đó giá trị mặc định của embed_resources là 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)
Lưu dưới dạng mẫu Outlook (.OFT)
Đoạn mã dưới đây cho bạn thấy cách lưu một tin nhắn dưới dạng tệp mẫu 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)