Gerenciar Anexos em Arquivos Outlook MSG
Aspose.Email for C++ fornece uma API rica para acessar, salvar, remover e incorporar anexos ao trabalhar com arquivos Microsoft Outlook MSG. Os anexos são manipulados através do MapiMessage classe, usando seu Attachments propriedade, que expõe um MapiAttachmentCollection.
Os exemplos neste artigo usam esses cabeçalhos e namespaces:
#include <MailMessage.h>
#include <SaveOptions.h>
#include <EmlSaveOptions.h>
#include <Mapi/MapiMessage.h>
#include <Mapi/MapiAttachment.h>
#include <Mapi/MapiAttachmentCollection.h>
#include <Mapi/MapiObjectProperty.h>
#include <Mapi/MapiPropertyCollection.h>
#include <Mapi/MailConversionOptions.h>
#include <Mapi/ReferenceAttachmentOptions.h>
#include <Mapi/InlineAttachmentExtractor.h>
#include <system/io/file.h>
#include <system/io/directory.h>
#include <system/io/path.h>
#include <system/io/memory_stream.h>
#include <system/convert.h>
using namespace System;
using namespace Aspose::Email;
using namespace Aspose::Email::Mapi;
Salvar Anexos de um Arquivo MSG
Para extrair e salvar anexos de um arquivo MSG:
- Carregue a mensagem usando MapiMessage::Load.
- Itere através do MapiAttachmentCollection retornado por
get_Attachments. - Salve cada anexo usando o MapiAttachment::Save() método.
SharedPtr<MapiMessage> message = MapiMessage::Load(u"MsgWithAtt.msg");
IO::Directory::CreateDirectory_(u"SavedAttachments");
for (SharedPtr<MapiAttachment> attachment : message->get_Attachments())
{
String path = IO::Path::Combine(u"SavedAttachments", attachment->get_LongFileName());
attachment->Save(path);
Console::WriteLine(u"Saved " + path);
}
Remover Anexos
Aspose.Email for C++ oferece dois métodos estáticos que removem os anexos de um arquivo de mensagem sem abri‑lo no seu código:
- RemoveAttachments recebe o caminho do arquivo de mensagem, analisa a mensagem e remove todos os anexos dela. Retorna os anexos que foram removidos.
- DestroyAttachments faz o mesmo sem analisar totalmente o arquivo MSG, o que o torna mais rápido.
Ambos os métodos alteram o arquivo no local, portanto o exemplo funciona em cópias.
IO::File::Copy(u"MsgWithAtt.msg", u"ToRemove.msg", true);
IO::File::Copy(u"MsgWithAtt.msg", u"ToDestroy.msg", true);
// parses the file and returns the attachments it removed
SharedPtr<MapiAttachmentCollection> removed = MapiMessage::RemoveAttachments(u"ToRemove.msg");
Console::WriteLine(u"Removed: " + Convert::ToString(removed->get_Count()));
// does the same without parsing the message, which is faster
MapiMessage::DestroyAttachments(u"ToDestroy.msg");
Console::WriteLine(u"Attachments left: " +
Convert::ToString(MapiMessage::Load(u"ToRemove.msg")->get_Attachments()->get_Count()) + u" / " +
Convert::ToString(MapiMessage::Load(u"ToDestroy.msg")->get_Attachments()->get_Count()));
Adicionar Anexos MSG
Arquivos MSG podem conter outros arquivos MSG como anexos padrão ou incorporados. A sobrecarga de MapiAttachmentCollection::Add que recebe um MapiMessage incorpora uma mensagem do Outlook; o Outlook então abre o anexo como mensagem em vez de como arquivo.
O código a seguir cria uma nova mensagem, anexa um arquivo MSG existente a ela como mensagem incorporada e salva o resultado.
SharedPtr<MapiMessage> message = MakeObject<MapiMessage>(u"from@test.com", u"to@test.com", u"Subj", u"This is a message body");
SharedPtr<MapiMessage> attachMsg = MapiMessage::Load(u"Message.msg");
message->get_Attachments()->Add(u"Weekly report.msg", attachMsg);
message->Save(u"WithEmbeddedMsg_out.msg");
SharedPtr<MapiAttachment> attachment = MapiMessage::Load(u"WithEmbeddedMsg_out.msg")->get_Attachments()->idx_get(0);
Console::WriteLine(attachment->get_DisplayName() + u" is an Outlook message: " + Convert::ToString(attachment->get_ObjectData()->get_IsOutlookMessage()));
Tell the Attachment Types Apart
O Outlook armazena cada anexo de uma mensagem no Anexos coleção, mas não são todos do mesmo tipo. IsInline marca os arquivos que o corpo exibe in‑line – imagens, principalmente – e IsReference aqueles que são apenas um link para um arquivo mantido em outro lugar.
SharedPtr<MapiMessage> message = MapiMessage::Load(u"messageWithEmbeddedEML.msg");
for (SharedPtr<MapiAttachment> attach : message->get_Attachments())
{
Console::WriteLine(attach->get_DisplayName() +
u" | inline: " + Convert::ToString(attach->get_IsInline()) +
u" | reference: " + Convert::ToString(attach->get_IsReference()) +
u" | file name: " + attach->get_LongFileName());
}
Add Files, Messages and References
MapiAttachmentCollection::Add tem uma sobrecarga para cada tipo de anexo: um array de bytes torna‑se um arquivo regular, um MapiMessage torna-se uma mensagem incorporada, e um ReferenceAttachmentOptions o objeto produz um link para um arquivo em armazenamento em nuvem – o link compartilhado, a localização do arquivo e o nome do provedor.
SharedPtr<MapiMessage> message = MakeObject<MapiMessage>(u"from@test.com", u"to@test.com",
u"Subj", u"This is a message body");
// a regular attachment from a byte array
message->get_Attachments()->Add(u"note.txt", IO::File::ReadAllBytes(u"description.html"));
// another Outlook message, embedded as an attachment
SharedPtr<MapiMessage> attachMsg = MapiMessage::Load(u"Message.msg");
message->get_Attachments()->Add(u"Weekly report.msg", attachMsg);
// a reference attachment: the file stays in the cloud storage
SharedPtr<ReferenceAttachmentOptions> options = MakeObject<ReferenceAttachmentOptions>(
u"https://drive.google.com/file/d/1HJ-M3F2qq1oRrTZ2GZhUdErJNy2CT3DF/",
u"https://drive.google.com/drive/my-drive",
u"GoogleDrive");
message->get_Attachments()->Add(u"Document.pdf", options);
message->Save(u"WithAttachments.msg");
Console::WriteLine(u"Attachments: " + Convert::ToString(message->get_Attachments()->get_Count()));
Read an Embedded Message
O conteúdo de uma mensagem incorporada é exposto através de ObjectData. IsOutlookMessage indica se o objeto realmente é uma mensagem, ToMapiMessage o retorna, e MapiMessage::FromProperties reconstrói-a a partir da coleção de propriedades brutas quando você precisa convertê-la mais adiante.
SharedPtr<MapiMessage> message = MapiMessage::Load(u"WithEmbeddedMsg.msg");
SharedPtr<MapiAttachment> attachment = message->get_Attachments()->idx_get(0);
if (attachment->get_ObjectData() != nullptr && attachment->get_ObjectData()->get_IsOutlookMessage())
{
// the embedded item as a MapiMessage
SharedPtr<MapiMessage> embedded = attachment->get_ObjectData()->ToMapiMessage();
Console::WriteLine(u"Embedded subject: " + embedded->get_Subject());
// the same item built from its properties and converted to MIME
SharedPtr<MapiMessage> fromProperties = MapiMessage::FromProperties(attachment->get_ObjectData()->get_Properties());
SharedPtr<MailMessage> eml = fromProperties->ToMailMessage(MakeObject<MailConversionOptions>());
eml->Save(u"NestedMailMessage.eml", SaveOptions::get_DefaultEml());
}
Insert, Replace and Rename Attachments
Além de anexar, a coleção pode colocar uma mensagem em uma posição escolhida com Insert e sobrescreve uma entrada existente com Substituir. O nome exibido no Outlook é o gravável NomeExibido propriedade.
SharedPtr<MapiMessage> message = MapiMessage::Load(u"WithAttachments.msg");
// take one of the embedded messages out
SharedPtr<IO::MemoryStream> memoryStream = MakeObject<IO::MemoryStream>();
message->get_Attachments()->idx_get(1)->Save(memoryStream);
memoryStream->set_Position(0);
SharedPtr<MapiMessage> extracted = MapiMessage::Load(memoryStream);
// put it back at a chosen position
message->get_Attachments()->Insert(1, u"inserted.msg", extracted);
// or overwrite the attachment that is already there
message->get_Attachments()->Replace(1, u"replaced.msg", extracted);
// the display name can be changed afterwards
message->get_Attachments()->idx_get(0)->set_DisplayName(u"New display name");
message->Save(u"RearrangedAttachments.msg");
for (SharedPtr<MapiAttachment> attach : MapiMessage::Load(u"RearrangedAttachments.msg")->get_Attachments())
{
Console::WriteLine(attach->get_DisplayName());
}
Replace sobrescreve uma entrada que existe; não pode criar uma em um índice além do final da coleção.
Extract OLE Objects from oledata.mso
Quando o corpo de uma mensagem é HTML em vez de RTF, o Outlook não armazena seus objetos OLE como anexos separados: eles acabam empacotados em um único oledata.mso anexo. InlineAttachmentExtractor::EnumerateMsoPackage divide esse pacote nos itens OLE individuais. Cada item é um Microsoft Compound Document; ler o documento em si – geralmente para extrair seu CONTENTS stream – é uma tarefa para uma biblioteca de arquivos compostos, que o Aspose.Email não inclui.
SharedPtr<MapiMessage> msg = MapiMessage::Load(u"messageWithEmbeddedEML.msg");
for (SharedPtr<MapiAttachment> attachment : msg->get_Attachments())
{
if (attachment->get_LongFileName() == u"oledata.mso")
{
// every entry is one OLE package in Compound File format
auto packages = InlineAttachmentExtractor::EnumerateMsoPackage(
MakeObject<IO::MemoryStream>(attachment->get_BinaryData()));
for (auto package : packages)
{
Console::WriteLine(package.get_Key() + u": " +
Convert::ToString(package.get_Value()->get_Length()) + u" bytes");
// hand the bytes to a library that reads Compound File documents
IO::File::WriteAllBytes(package.get_Key(), package.get_Value());
}
}
}
Acessar um Anexo Recém‑adicionado
O Adicionar métodos de MapiAttachmentCollection classe retorna o MapiAttachment objeto que criam. Isso dá acesso imediato ao novo anexo, para que você possa configurá‑lo logo após a inserção sem procurar na coleção por ele. As sobrecargas a seguir retornam o anexo criado:
Add(String name, ArrayPtr<uint8_t> data)- adiciona um anexo regular a partir de um array de bytes.Add(String name, SharedPtr<MapiMessage> msg)- adiciona uma mensagem do Outlook como anexo incorporado.Add(String name, SharedPtr<ReferenceAttachmentOptions> options)- adiciona um anexo de referência.
O código a seguir adiciona um anexo regular e uma mensagem incorporada e altera seus nomes de exibição com set_DisplayName():
#include <Mapi/MapiMessage.h>
#include <Mapi/MapiAttachment.h>
#include <Mapi/MapiAttachmentCollection.h>
#include <system/io/file.h>
using namespace System;
using namespace Aspose::Email::Mapi;
auto message = MakeObject<MapiMessage>(u"from@domain.com", u"to@domain.com", u"Weekly report", u"Please find the files attached.");
// Add a regular attachment and change its display name
SharedPtr<MapiAttachment> attachment = message->get_Attachments()->Add(u"invoice.pdf", IO::File::ReadAllBytes(u"invoice.pdf"));
attachment->set_DisplayName(u"Invoice #2026-001.pdf");
// Add an embedded message and change its display name
SharedPtr<MapiAttachment> embedded = message->get_Attachments()->Add(u"original.msg", MapiMessage::Load(u"message.msg"));
embedded->set_DisplayName(u"Original request");
message->Save(u"report.msg");