Gestione degli allegati nei messaggi Outlook
Il Creare e salvare file Outlook Message (MSG) l’articolo spiegava i passaggi per creare e salvare messaggi, inclusi file MSG con allegati. Questo articolo approfondisce la gestione degli allegati Microsoft Outlook usando Aspose.Email. Ti guiderà nell’accesso e nel salvataggio degli allegati da un file di messaggio utilizzando il attachments proprietà del MapiMessage classe. Questa proprietà è una collezione appartenente al MapiAttachmentCollection classe, che consente una gestione efficiente degli allegati.
Verificare allegati Inline vs Regular
"Inline" e "Regular" si riferiscono al modo in cui sono inclusi in un messaggio email. Gli allegati Regular sono file allegati nel modo tradizionale. Solitamente vengono visualizzati in un elenco all’interno del client email e possono essere scaricati dal destinatario e salvati in una memoria locale. Gli allegati Inline, noti anche come immagini incorporate o inline, vengono solitamente utilizzati per includere immagini o altri media nel corpo dell’email. Non sono visualizzati in un elenco separato ma mostrati direttamente nel contenuto dell’email, ad esempio nel corpo del messaggio. Ciò consente di includere immagini o altri media che fanno parte del contenuto del messaggio. Il seguente esempio di codice dimostra come determinare se un allegato è inline o regular:
import aspose.email as ae
msg = ae.mapi.MapiMessage.load("message.msg")
for attachment in msg.attachments:
print(f"{attachment.display_name}:{attachment.is_inline}")
Identificare gli allegati di riferimento nei messaggi MAPI
L’API Aspose.Email include il is_reference proprietà del MapiAttachment classe che consente agli sviluppatori di identificare gli allegati di riferimento in un messaggio. Prova l’esempio di codice qui sotto per vedere come funziona in un progetto python:
import aspose.email as ae
# Load or create a MapiMessage
msg = ae.mapi.MapiMessage.load("Message_With_Reference_Attachment.msg")
# Iterate through the attachments
for attachment in msg.attachments:
if attachment.is_reference:
# Process reference attachment
pass
Salvare gli allegati da file MSG
Per salvare gli allegati da un file MSG:
- Iterare attraverso il MapiAttachmentCollection collezione e ottieni gli allegati individuali.
- Per salvare gli allegati, chiama il MapiAttachment classe Save() metodo.
Il seguente snippet di codice mostra come salvare gli allegati su disco locale:
import aspose.email as ae
data_dir = "C://dataDir/"
file_name = "message.msg"
# Create an instance of MapiMessage from file
message = ae.mapi.MapiMessage.load(data_dir + file_name)
# Iterate through the attachments collection
for attachment in message.attachments:
# Save the individual attachment
attachment.save(data_dir + attachment.file_name)
Gestione degli allegati TNEF
Caricare e salvare allegati in formato TNEF
Aspose.Email fornisce metodi per gestire gli allegati TNEF. Questi metodi consentono di salvare e caricare allegati in formato TNEF, comunemente usato nei messaggi Outlook (winmail.dat).
- static MapiAttachment MapiAttachment.load_from_tnef(string fileName) – Carica un allegato da un file TNEF.
- static MapiAttachment MapiAttachment.load_from_tnef(Stream stream) – Carica un allegato da un flusso TNEF.
- void MapiAttachment.save_to_tnef(string filename) – Salva un allegato in un file TNEF.
- void MapiAttachment.save_to_tnef(Stream stream) – Salva un allegato in un flusso TNEF.
Il seguente esempio di codice dimostra come estrarre, salvare e ri-aggiungere allegati email in formato TNEF gestendoli tramite stream di memoria o file:
import io
from aspose.email.mapi import MapiMessage, MapiAttachment
# Load the EML message (which contains a winmail.dat TNEF attachment)
msg = MapiMessage.load("message.eml")
# Save the first attachment as a winmail.dat file
msg.attachments[0].save_to_tnef("winmail.dat")
# Load the TNEF attachment from the file and add it back to the message
from_tnef_attachment = MapiAttachment.load_from_tnef("winmail.dat")
msg.attachments.add(from_tnef_attachment.long_file_name, from_tnef_attachment.binary_data)
# (Optional) If you also want to use a memory stream instead of the file
ms = io.BytesIO()
msg.attachments[0].save_to_tnef(ms)
# Reset the stream position to the beginning
ms.seek(0)
# Load the TNEF attachment directly from the memory stream and add it
from_tnef_attachment_from_stream = MapiAttachment.load_from_tnef(ms)
msg.attachments.add(from_tnef_attachment_from_stream.long_file_name, from_tnef_attachment_from_stream.binary_data)
Recuperare gli allegati di messaggi di posta annidati
Gli allegati OLE incorporati (Object Linking and Embedding) compaiono anche nella raccolta di allegati del MapiMessage classe. L’esempio di codice qui sotto dimostra come analizzare un file di messaggio ed estrarre gli allegati di messaggi incorporati, salvandoli successivamente su disco per un uso successivo. Il MapiMessage classe offre un from_properties metodo statico per creare un nuovo messaggio da un allegato incorporato. Il seguente snippet di codice mostra come ottenere gli allegati di messaggi di posta annidati:
import aspose.email as ae
eml = ae.mapi.MapiMessage.load("my.msg")
# Create a MapiMessage object from the individual attachment
get_attachment = ae.mapi.MapiMessage.from_properties(eml.attachments[0].object_data.properties)
# Create an object of type MailMessageInterpreter from the above message and save the embedded message to a file on disk
mail_message = get_attachment.to_mail_message(ae.mapi.MailConversionOptions())
mail_message.save("NestedMailMessageAttachments_out.eml", ae.SaveOptions.default_eml)
Rimuovere allegati
La libreria Aspose.Email fornisce la funzionalità per rimuovere gli allegati dai file Microsoft Outlook Message (.msg). Utilizza il remove_attachments(path) metodo che richiede il percorso del file del messaggio come parametro. In quanto metodo statico pubblico, può essere chiamato direttamente senza necessità di istanziare un oggetto, rendendo il processo semplice ed efficiente.
Il seguente snippet di codice mostra come rimuovere gli allegati dai file MSG usando Aspose.Email:
import aspose.email as ae
ae.mapi.MapiMessage.remove_attachments("AttachmentsToRemove_out.msg")
È inoltre possibile chiamare il metodo statico destroy_attachments del MapiMessage classe. Funziona più velocemente di remove_attachments perché il metodo remove_attachments analizza il file del messaggio.
import aspose.email as ae
# Destroy attachments in the MapiMessage
ae.mapi.MapiMessage.destroy_attachments("AttachmentsToDestroy_out.msg")
Aggiungere allegati MSG
Un messaggio Outlook può contenere altri messaggi Microsoft Outlook come allegati, sia regolari sia incorporati. Il MapiAttachmentCollection fornisce membri sovraccaricati del aggiungi metodo per creare messaggi Outlook con entrambi i tipi di allegati.
Provalo!
Aggiungi o rimuovi allegati email online con il gratuito App Aspose.Email Editor.
Aggiungere allegati di riferimento ai messaggi MAPI
Allegato di riferimento si riferisce tipicamente a un allegato che contiene un riferimento o link a una risorsa esterna piuttosto che al file effettivo. Questi riferimenti sono spesso usati nelle email HTML per collegare a immagini o risorse esterne ospitate su un server remoto. Invece di incorporare l’intero file, un allegato di riferimento include un URL o un riferimento al contenuto esterno.
Per aggiungere un allegato di riferimento a un messaggio MAPI, utilizzare il add metodo del MapiAttachmentCollection classe e il ReferenceAttachmentOptions classe per specificare:
-
L’URL del contenuto (link diretto al file)
-
L’URL del provider (link alla posizione del file o visualizzazione UI)
-
Il nome del provider di allegati (es., "GoogleDrive")
come mostrato nel seguente esempio di codice.
import aspose.email as ae
# Load or create a MapiMessage
msg = ae.mapi.MapiMessage()
msg.subject = "Email with Reference Attachment"
msg.body = "This message contains a cloud-based reference attachment."
# Create ReferenceAttachmentOptions
options = ae.mapi.ReferenceAttachmentOptions(
"https://drive.google.com/file/d/1HJ-M3F2qq1oRrTZ2GZhUdErJNy2CT3DF/",
"https://drive.google.com/drive/my-drive",
"GoogleDrive"
)
# Add the reference attachment to the message
msg.attachments.add("Document.pdf", options)
# Save the message to MSG format
msg.save("Message_With_Reference_Attachment.msg")
Incorporare messaggi come allegati
Il seguente snippet di codice dimostra come incorporare file Outlook MSG come allegati all’interno di un altro file MSG. Un file MSG incorporato include una proprietà PR_ATTACH_METHOD con valore 5, indicando che è un allegato di tipo "message".
import aspose.email as ae
# Create a new MapiMessage
message = ae.mapi.MapiMessage("from@test.com", "to@test.com", "Subj", "This is a message body")
# Load the attachment message
attach_msg = ae.mapi.MapiMessage.load("Message.msg")
# Add the attachment to the message
message.attachments.add("Weekly report.msg", attach_msg)
# Save the message with the embedded message attachment
message.save("WithEmbeddedMsg_out.msg")
Leggere messaggi incorporati dagli allegati
Il seguente snippet di codice mostra come leggere i messaggi incorporati dagli allegati.
import aspose.email as ae
file_name = "path/to/file.msg"
# Load the MapiMessage from file
message = ae.mapi.MapiMessage.load(file_name)
# Check if the first attachment is an Outlook message
if message.attachments[0].object_data.is_outlook_message:
# Get the embedded message as MapiMessage
embedded_message = message.attachments[0].object_data.to_mapi_message()
# Perform further operations with the embedded message
# ...
Inserire e sostituire allegati
L’API Aspose.Email offre la funzionalità di inserire allegati a un indice specifico all’interno del messaggio principale. Inoltre, fornisce la possibilità di sostituire il contenuto di un allegato esistente con un diverso allegato di messaggio. Di seguito sono riportati snippet di codice che mostrano come eseguire l’inserimento e la sostituzione degli allegati.
Inserire allegati in posizioni specifiche
L’API Aspose.Email consente di inserire un allegato MSG in un MSG principale usando il metodo Insert del MapiAttachmentCollection. Questo metodo è usato con la firma MapiAttachmentCollection Insert(int index, string name, MapiMessage msg). Di seguito è mostrato uno snippet di codice che illustra come inserire un allegato in una posizione specifica:
import aspose.email as ae
from io import BytesIO
file_name = "path/to/file.msg"
# Load the MapiMessage from file
message = ae.mapi.MapiMessage.load(file_name)
# Save the attachment to a memory stream
memory_stream = BytesIO()
message.attachments[2].save(memory_stream)
# Load the attachment from the memory stream
get_data = ae.mapi.MapiMessage.load(memory_stream)
# Insert the loaded attachment at index 1
message.attachments.insert(1, "new 11", get_data)
Sostituire i contenuti dell’allegato
È possibile utilizzare il replace metodo per aggiornare il contenuto di un allegato incorporato con nuovi dati. Tuttavia, si noti che questo metodo non può essere usato per inserire un allegato con PR_ATTACH_NUM = 4 in una collezione che contiene solo 2 allegati. Di seguito è riportato uno snippet di codice che dimostra come sostituire il contenuto di un allegato:
import aspose.email as ae
from io import BytesIO
file_name = "path/to/file.msg"
# Load the MapiMessage from file
message = ae.mapi.MapiMessage.load(file_name)
# Save the attachment to a memory stream
memory_stream = BytesIO()
message.attachments[2].save(memory_stream)
# Load the attachment from the memory stream
get_data = ae.mapi.MapiMessage.load(memory_stream)
# Replace the attachment at index 1 with the loaded attachment
message.attachments.replace(1, "new 1", get_data)
Rinominare gli allegati in MapiMessages
Con Aspose.Email, è possibile modificare facilmente i nomi visualizzati degli allegati nei messaggi email caricati da un file. Il seguente esempio di codice dimostra come ottenere questo risultato:
import aspose.email as ae
msg = ae.mapi.MapiMessage.load("message.msg")
msg.attachments[0].display_name = "New display name 1"
msg.attachments[1].display_name = "New display name 2"