Caricamento, salvataggio e conversione delle email

Rilevare i formati dei file email

L’API Aspose.Email fornisce la capacità di rilevare il formato del file del messaggio fornito. Il DetectFileFormat metodo di FileFormatUtil La classe può essere usata per ottenere ciò. Le classi e i metodi seguenti possono essere usati per rilevare il formato del file caricato:

Il seguente frammento di codice mostra come rilevare i formati dei file:

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

Caricamento di un messaggio con opzioni di caricamento

Il seguente frammento di codice mostra come caricare un messaggio con le opzioni di caricamento.

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)

Preservare il formato dei messaggi incorporati durante il caricamento

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

Salvataggio e conversione delle email

Aspose.Email rende facile convertire qualsiasi tipo di messaggio in un altro formato. Per dimostrare questa funzionalità, il codice in questo articolo carica tre tipi di messaggi dal disco e li salva nuovamente in altri formati. La classe base SaveOptions e le classi EmlSaveOptions, MsgSaveOptions, MhtSaveOptions, HtmlSaveOptions può essere usato per impostazioni aggiuntive quando si salvano messaggi in altri formati. L’articolo mostra come usare queste classi per salvare un’email di esempio come:

  • Formato EML.
  • Outlook MSG.
  • Formato MHTML.
  • Formato HTML.

Salvataggio come EML

Il seguente frammento di codice mostra come caricare un messaggio EML e salvarlo su disco nello stesso formato.

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)

Preservare i confini nei file EML

Il seguente frammento di codice mostra come caricare un file EML e salvarlo nello stesso formato preservando i confini originali.

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)

Personalizzare le stringhe di confine MIME

Aspose.Email per .NET consente di configurare il modello di confine utilizzato nei messaggi MIME. Questo è ottenuto attraverso il boundaries_template proprietà del EmlSaveOptions classe.

Impostando un modello personalizzato, è possibile definire come vengono generati i confini MIME. Il carattere jolly {#} nel modello verrà sostituito con un numero di confine incrementale, consentendo stringhe di confine dinamiche e leggibili.

Se boundaries_template non è impostato (il valore predefinito è None), la libreria utilizza il suo formato di confine interno.

Il seguente esempio di codice mostra come personalizzare le stringhe di confine MIME quando si salva un messaggio email nel formato .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)

Ecco un esempio della struttura del messaggio con confini personalizzati salvati usando il codice mostrato sopra:

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

Preservare gli allegati TNEF nei file EML

Il seguente frammento di codice mostra come salvare un file EML preservando gli allegati 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)

Salvataggio come MSG

Il seguente frammento di codice mostra come caricare un messaggio EML e convertirlo in MSG usando l’opzione appropriata da 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)

Preservare le date nei file MSG

Il MsgSaveOptions la classe consente di salvare il messaggio sorgente come file Outlook Message (MSG) preservando le date. Il seguente frammento di codice mostra come salvare un file EML come MSG e preservare le date.

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)

Salvataggio come MHTML

Diverse opzioni di MHTML possono essere usate per ottenere i risultati desiderati. Il frammento di codice seguente ti mostra come caricare un messaggio EML in MailMessage e convertirlo in 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)

Impostazioni personalizzate di conversione MHTML

Il MhtSaveOptions la classe fornisce opzioni aggiuntive per salvare i messaggi email in formato MHTML. L’enumeratore MhtFormatOptions consente di scrivere informazioni email aggiuntive nel MHTML di output. I seguenti campi aggiuntivi possono essere scritti:

  • NONE - Nessuna impostazione specifica è specificata.
  • WRITE_HEADER - Indica che le informazioni dell’intestazione dovrebbero essere scritte.
  • WRITE_OUTLINE_ATTACHMENTS - Indica che gli allegati outline dovrebbero essere scritti.
  • WRITE_COMPLETE_EMAIL_ADDRESS - Indica che l’indirizzo email completo dovrebbe essere scritto in tutte le intestazioni email.
  • NO_ENCODE_CHARACTERS - Indica che non dovrebbe essere usata alcuna codifica di trasferimento dei caratteri.
  • HIDE_EXTRA_PRINT_HEADER - Indica che PageHeader sarà invisibile.
  • WRITE_COMPLETE_TO_EMAIL_ADDRESS - Indica che l’indirizzo email completo dovrebbe essere scritto nell’intestazione ‘To’.
  • WRITE_COMPLETE_FROM_EMAIL_ADDRESS - Indica che l’indirizzo email completo dovrebbe essere scritto nell’intestazione ‘From’.
  • WRITE_COMPLETE_CC_EMAIL_ADDRESS - Indica che l’indirizzo email completo dovrebbe essere scritto nell’intestazione ‘Cc’.
  • WRITE_COMPLETE_BCC_EMAIL_ADDRESS - Indica che l’indirizzo email completo dovrebbe essere scritto nell’intestazione ‘Bcc’.
  • RENDER_CALENDAR_EVENT - Indica che il testo dell’evento del calendario dovrebbe essere scritto nell’mhtml di output.
  • SKIP_BYTE_ORDER_MARK_IN_BODY - Indica che i byte Byte Order Mark (BOM) dovrebbero essere scritti nel corpo.
  • RENDER_V_CARD_INFO - Indica che il testo da VCard AlternativeView dovrebbe essere scritto nell’mhtml di output.
  • DISPLAY_AS_OUTLOOK - Indica che l’intestazione From sarà visualizzata come in Outlook.
  • RENDER_TASK_FIELDS - Indica che i campi specifici del Task dovrebbero essere scritti nell’mhtml di output.

Il seguente frammento di codice mostra come convertire un file EML in MHTML con impostazioni opzionali.

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)

Inclusione degli eventi del calendario nella conversione MHTML

Il MhtFormatOptions.RenderCalendarEvent renderizza gli eventi del Calendario nell’output MHTML. Il seguente frammento di codice mostra come renderizzare gli eventi del calendario durante la conversione in 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)

Esportazione dell’email in MHT senza immagini in linea

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)

Esportazione dell’email in MHT con fuso orario personalizzato

MailMessage classe fornisce il TimeZoneOffset proprietà per impostare un fuso orario personalizzato durante l’esportazione in MHT. Il seguente frammento di codice mostra come esportare un’email in MHT con fuso orario personalizzato:

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)

Salvataggio come HTML

Il HtmlSaveOptions la classe consente di esportare il corpo del messaggio in HTML con l’opzione di salvare le risorse incorporate. Il seguente frammento di codice mostra come salvare un messaggio come HTML dove il valore predefinito di 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)

Salvataggio come modello Outlook (.OFT)

Il seguente frammento di codice mostra come salvare un messaggio come file modello 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)