Ładowanie, zapisywanie i konwertowanie e‑maili

Wykrywanie formatów plików e-mail

API Aspose.Email zapewnia możliwość wykrywania formatu pliku podanej wiadomości. DetectFileFormat metoda FileFormatUtil klasa może być użyta do osiągnięcia tego. Poniższe klasy i metody mogą być użyte do wykrycia formatu wczytanego pliku:

Poniższy fragment kodu pokazuje, jak wykrywać formaty plików:

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))

Ładowanie wiadomości z opcjami ładowania

Poniższy fragment kodu pokazuje, jak wczytać wiadomość z opcjami ładowania.

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)

Zachowywanie formatu wbudowanej wiadomości podczas ładowania

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))

Zapisywanie i konwertowanie e‑maili

Aspose.Email ułatwia konwertowanie dowolnego typu wiadomości na inny format. Aby zademonstrować tę funkcję, kod w tym artykule ładuje trzy typy wiadomości z dysku i zapisuje je ponownie w innych formatach. Klasa bazowa SaveOptions oraz klasy EmlSaveOptions, MsgSaveOptions, MhtSaveOptions, HtmlSaveOptions może być użyte do dodatkowych ustawień przy zapisywaniu wiadomości w innych formatach. Artykuł pokazuje, jak używać tych klas do zapisania przykładowego e‑maila jako:

  • format EML.
  • Outlook MSG.
  • format MHTML.
  • format HTML.

Zapisywanie jako EML

Poniższy fragment kodu pokazuje, jak wczytać wiadomość EML i zapisać ją na dysku w tym samym formacie.

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)

Zachowywanie granic w plikach EML

Poniższy fragment kodu pokazuje, jak wczytać plik EML i zapisać go w tym samym formacie, zachowując oryginalne granice.

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)

Dostosowywanie ciągów granic MIME

Aspose.Email for .NET umożliwia skonfigurowanie szablonu granicy używanego w wiadomościach MIME. Jest to realizowane poprzez boundaries_template właściwość EmlSaveOptions klasa.

Ustawiając własny szablon, możesz zdefiniować sposób generowania granic MIME. Symbol wieloznaczny {#} w szablonie zostanie zastąpiony kolejno rosnącym numerem granicy, co umożliwia tworzenie dynamicznych i czytelnych ciągów granic.

Jeśli boundaries_template nie jest ustawione (domyślnie None), biblioteka używa własnego formatu granic.

Poniższy przykład kodu pokazuje, jak dostosować ciągi granic MIME przy zapisywaniu wiadomości e‑mail w formacie .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)

Oto przykład struktury wiadomości z niestandardowymi ograniczeniami zapisany przy użyciu powyższego kodu:

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--

Zachowywanie załączników TNEF w plikach EML

Poniższy fragment kodu pokazuje, jak zapisać plik EML zachowując załączniki 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)

Zapisywanie jako MSG

Poniższy fragment kodu pokazuje, jak wczytać wiadomość EML i przekonwertować ją na MSG, używając odpowiedniej opcji z 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)

Zachowywanie dat w plikach MSG

Ten MsgSaveOptions klasa umożliwia zapisanie źródłowej wiadomości jako pliku Outlook Message (MSG) zachowując daty. Poniższy fragment kodu pokazuje, jak zapisać plik EML jako MSG i zachować daty.

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)

Zapisywanie jako MHTML

Różne opcje MHTML mogą być użyte do uzyskania pożądanych rezultatów. Poniższy fragment kodu pokazuje, jak załadować wiadomość EML do MailMessage i skonwertować go do 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)

Niestandardowe ustawienia konwersji MHTML

Ten MhtSaveOptions klasa zapewnia dodatkowe opcje zapisywania wiadomości e‑mail w formacie MHTML. Enumerator MhtFormatOptions umożliwia zapis dodatkowych informacji e‑mail do wyjściowego MHTML. Można zapisać następujące dodatkowe pola:

  • NONE – nie określono żadnych konkretnych ustawień.
  • WRITE_HEADER – wskazuje, że informacje nagłówka powinny być zapisane.
  • WRITE_OUTLINE_ATTACHMENTS – wskazuje, że załączniki zarysowe powinny być zapisane.
  • WRITE_COMPLETE_EMAIL_ADDRESS – wskazuje, że pełny adres e‑mail powinien być zapisany we wszystkich nagłówkach e‑mail.
  • NO_ENCODE_CHARACTERS – wskazuje, że nie należy używać kodowania znaków przy przesyłaniu.
  • HIDE_EXTRA_PRINT_HEADER – wskazuje, że PageHeader będzie niewidoczny.
  • WRITE_COMPLETE_TO_EMAIL_ADDRESS – wskazuje, że pełny adres e‑mail powinien być zapisany w nagłówku ‘To’.
  • WRITE_COMPLETE_FROM_EMAIL_ADDRESS – wskazuje, że pełny adres e‑mail powinien być zapisany w nagłówku ‘From’.
  • WRITE_COMPLETE_CC_EMAIL_ADDRESS – wskazuje, że pełny adres e‑mail powinien być zapisany w nagłówku ‘Cc’.
  • WRITE_COMPLETE_BCC_EMAIL_ADDRESS – wskazuje, że pełny adres e‑mail powinien być zapisany w nagłówku ‘Bcc’.
  • RENDER_CALENDAR_EVENT – wskazuje, że tekst z wydarzenia kalendarza powinien być zapisany w wyjściowym mhtml.
  • SKIP_BYTE_ORDER_MARK_IN_BODY – wskazuje, że bajty Byte Order Mark (BOM) powinny być zapisane w treści.
  • RENDER_V_CARD_INFO – wskazuje, że tekst z AlternativeView VCard powinien być zapisany w wyjściowym mhtml.
  • DISPLAY_AS_OUTLOOK – wskazuje, że nagłówek From będzie wyświetlany tak jak w Outlooku.
  • RENDER_TASK_FIELDS – wskazuje, że określone pola zadania powinny być zapisane w wyjściowym mhtml.

Poniższy fragment kodu pokazuje, jak konwertować plik EML do MHTML z opcjonalnymi ustawieniami.

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)

Dołączanie wydarzeń kalendarza w konwersji do MHTML

Ten MhtFormatOptions.RenderCalendarEvent renderuje wydarzenia Kalendarza do wyjściowego MHTML. Poniższy fragment kodu pokazuje, jak renderować wydarzenia kalendarza podczas konwersji do 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)

Eksport e‑maila do MHT bez obrazów w treści

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)

Eksport e‑maila do MHT z niestandardową strefą czasową

MailMessage klasa udostępnia TimeZoneOffset właściwość służy do ustawienia niestandardowej strefy czasowej podczas eksportu do MHT. Poniższy fragment kodu pokazuje, jak wyeksportować e‑mail do MHT z niestandardową strefą czasową:

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)

Zapisywanie jako HTML

Ten HtmlSaveOptions klasa umożliwia eksport treści wiadomości do HTML z opcją zapisu osadzonych zasobów. Poniższy fragment kodu pokazuje, jak zapisać wiadomość jako HTML, przy czym domyślna wartość embed_resources to 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)

Zapisywanie jako szablon Outlook (.OFT)

Poniższy fragment kodu pokazuje, jak zapisać wiadomość jako szablon Outlooka (.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)