Работа с MAPI свойствами с использованием библиотеки Email C++

Доступ и установка свойства MAPI Outlook

Класс MapiProperty представляет собой свойство MAPI, которое содержит:

  • Имя: строка, представляющая имя свойства.
  • Тег: длинное целое число, представляющее тег свойства.
  • Данные: массив байтов, представляющий данные свойства.

Получение свойства MAPI с помощью тега свойства MAPI

Чтобы получить свойства MAPI:

  1. Создайте экземпляр MapiMessage, загружая его из файлов или потока.
  2. Получите MapiProperty из MapiMessage.Properties по ключам MapiPropertyTag.
  3. Получите данные MapiProperty с помощью метода GetX.

Следующий фрагмент кода показывает, как получить свойство MAPI с использованием тега свойства MAPI с библиотекой C++ Email Parser.

For complete examples and data files, please go to https://github.com/kashifiqb/Aspose.Email-for-C
// The path to the File directory.
System::String dataDir = RunExamples::GetDataDir_Outlook();
// Load from file
System::SharedPtr<MapiMessage> msg = MapiMessage::FromFile(dataDir + L"message.msg");
System::String subject;
// Access the MapiPropertyTag.PR_SUBJECT property
System::SharedPtr<MapiProperty> prop = msg->get_Properties()->idx_get(MapiPropertyTag::PR_SUBJECT);
// If the property is not found, check the MapiPropertyTag.PR_SUBJECT_W (which is a // Unicode peer of the MapiPropertyTag.PR_SUBJECT)
if (prop == nullptr)
{
prop = msg->get_Properties()->idx_get(MapiPropertyTag::PR_SUBJECT_W);
}
// Cannot found
if (prop == nullptr)
{
System::Console::WriteLine(L"No property found!");
return;
}
// Get the property data as string
subject = prop->GetString();
System::Console::WriteLine(System::String(L"Subject:") + subject);
// Read internet code page property
prop = msg->get_Properties()->idx_get(MapiPropertyTag::PR_INTERNET_CPID);
if (prop != nullptr)
{
System::Console::WriteLine(System::String(L"CodePage:") + prop->GetLong());
}

Установка свойств MAPI

Следующий фрагмент кода показывает, как установить свойства MAPI.

For complete examples and data files, please go to https://github.com/kashifiqb/Aspose.Email-for-C
// The path to the File directory.
System::String dataDir = RunExamples::GetDataDir_Outlook();
// Create a sample Message
System::SharedPtr<MapiMessage> mapiMsg = System::MakeObject<MapiMessage>(L"user1@gmail.com", L"user2@gmail.com", L"This is subject", L"This is body");
// Set multiple properties
System::StaticCast<MapiMessageItemBase>(mapiMsg)->SetProperty(System::MakeObject<MapiProperty>(MapiPropertyTag::PR_SENDER_ADDRTYPE_W, System::Text::Encoding::get_Unicode()->GetBytes(L"EX")));
System::SharedPtr<MapiRecipient> recipientTo = mapiMsg->get_Recipients()->idx_get(0);
System::SharedPtr<MapiProperty> propAddressType = System::MakeObject<MapiProperty>(MapiPropertyTag::PR_RECEIVED_BY_ADDRTYPE_W, System::Text::Encoding::get_UTF8()->GetBytes(L"MYFAX"));
recipientTo->SetProperty(propAddressType);
System::String faxAddress = L"My Fax User@/FN=fax#/VN=voice#/CO=My Company/CI=Local";
System::SharedPtr<MapiProperty> propEmailAddress = System::MakeObject<MapiProperty>(MapiPropertyTag::PR_RECEIVED_BY_EMAIL_ADDRESS_W, System::Text::Encoding::get_UTF8()->GetBytes(faxAddress));
recipientTo->SetProperty(propEmailAddress);
mapiMsg->SetMessageFlags(Aspose::Email::Outlook::MapiMessageFlags::MSGFLAG_UNSENT | Aspose::Email::Outlook::MapiMessageFlags::MSGFLAG_FROMME);
System::StaticCast<MapiMessageItemBase>(mapiMsg)->SetProperty(System::MakeObject<MapiProperty>(MapiPropertyTag::PR_RTF_IN_SYNC, System::BitConverter::GetBytes((int64_t)1)));
// Set DateTime property
System::SharedPtr<MapiProperty> modificationTime = System::MakeObject<MapiProperty>(MapiPropertyTag::PR_LAST_MODIFICATION_TIME, ConvertDateTime(System::DateTime(2013, 9, 11)));
System::StaticCast<MapiMessageItemBase>(mapiMsg)->SetProperty(modificationTime);
mapiMsg->Save(dataDir + L"MapiProp_out.msg");

где определение метода convertDateTime выглядит следующим образом:


 int64_t filetime = t.ToFileTime();

System::ArrayPtr<uint8_t> d = System::MakeArray<uint8_t>(8, 0);

d[0] = (uint8_t)(filetime & 0xFF);

d[1] = (uint8_t)((filetime & 0xFF00) >> 8);

d[2] = (uint8_t)((filetime & 0xFF0000) >> 16);

d[3] = (uint8_t)((filetime & 0xFF000000) >> 24);

d[4] = (uint8_t)((filetime & 0xFF00000000) >> 32);

d[5] = (uint8_t)((filetime & 0xFF0000000000) >> 40);

d[6] = (uint8_t)((filetime & 0xFF000000000000) >> 48);

d[7] = (uint8_t)(((uint64_t)filetime & 0xFF00000000000000) >> 56);

Чтение именованных свойств MAPI из файлов MSG Outlook

Microsoft Outlook поддерживает добавление именованных свойств MAPI в файл MSG. Эти именованные свойства MAPI добавляются пользователем. Вы можете добавить именованное свойство, например “MyProp”, в файл MSG, используя Aspose.Email. Эта статья иллюстрирует возможности Aspose.Email:

  • Чтение именованных свойств MAPI из файла MSG Outlook
  • Чтение свойств из вложений
  • Удаление свойств из MSG и вложений

Чтение именованных свойств MAPI из файла MSG

Следующий фрагмент кода показывает, как читать именованные свойства MAPI из файла MSG.

For complete examples and data files, please go to https://github.com/kashifiqb/Aspose.Email-for-C
// The path to the File directory.
System::String dataDir = RunExamples::GetDataDir_Outlook();
// Load from file
System::SharedPtr<MapiMessage> message = MapiMessage::FromFile(dataDir + L"message.msg");
// Get all named MAPI properties
System::SharedPtr<MapiPropertyCollection> properties = message->get_NamedProperties();
// Read all properties in foreach loop
{
auto mapiNamedProp_enumerator = (System::DynamicCastEnumerableTo<System::SharedPtr<MapiNamedProperty>>(properties->get_Values()))->GetEnumerator();
decltype(mapiNamedProp_enumerator->get_Current()) mapiNamedProp;
while (mapiNamedProp_enumerator->MoveNext() && (mapiNamedProp = mapiNamedProp_enumerator->get_Current(), true))
{
// Read any specific property
{
const System::String switch_value_0 = mapiNamedProp->get_NameId();
do {
if (switch_value_0 == L"TEST")
{
System::Console::WriteLine(L"{0} = {1}", System::ObjectExt::Box<System::String>(mapiNamedProp->get_NameId()), System::ObjectExt::Box<System::String>(mapiNamedProp->GetString()));
break;
}
if (switch_value_0 == L"MYPROP")
{
System::Console::WriteLine(L"{0} = {1}", System::ObjectExt::Box<System::String>(mapiNamedProp->get_NameId()), System::ObjectExt::Box<System::String>(mapiNamedProp->GetString()));
break;
}
if (true)
{
break;
}
} while (false);
}
}
}

Чтение именованного свойства MAPI из вложения

Aspose.Email также позволяет вам просматривать свойства MapiAttachment и искать именованное свойство, подобно примеру выше, для MapiMessage. Следующий фрагмент кода показывает, как искать именованное свойство через коллекцию свойств вложения.

For complete examples and data files, please go to https://github.com/kashifiqb/Aspose.Email-for-C
// The path to the File directory.
System::String dataDir = RunExamples::GetDataDir_Outlook();
// Load from file
System::SharedPtr<MailMessage> mail = MailMessage::Load(dataDir + L"outputAttachments.msg");
auto mapi = MapiMessage::FromMailMessage(mail);
{
auto namedProperty_enumerator = (System::DynamicCastEnumerableTo<System::SharedPtr<MapiNamedProperty>>(mapi->get_Attachments()->idx_get(0)->get_NamedProperties()->get_Values()))->GetEnumerator();
decltype(namedProperty_enumerator->get_Current()) namedProperty;
while (namedProperty_enumerator->MoveNext() && (namedProperty = namedProperty_enumerator->get_Current(), true))
{
if (System::String::Compare(namedProperty->get_NameId(), L"CustomAttGuid", System::StringComparison::OrdinalIgnoreCase) == 0)
{
return namedProperty->GetString();
}
}
}
return System::String::Empty;

Удаление свойств из MSG и вложений

Следующий фрагмент кода показывает, как удалить свойства из MSG и вложений.

For complete examples and data files, please go to https://github.com/kashifiqb/Aspose.Email-for-C
// The path to the File directory.
System::String dataDir = RunExamples::GetDataDir_Outlook();
System::SharedPtr<MapiMessage> mapi = System::MakeObject<MapiMessage>(L"from@doamin.com", L"to@domain.com", L"subject", L"body");
mapi->SetBodyContent(L"<html><body><h1>This is the body content</h1></body></html>", Aspose::Email::Outlook::BodyContentType::Html);
System::SharedPtr<MapiMessage> attachment = MapiMessage::FromFile(dataDir + L"message.msg");
mapi->get_Attachments()->Add(L"Outlook2 Test subject.msg", attachment);
System::Console::WriteLine(System::String(L"Before removal = ") + mapi->get_Attachments()->idx_get(mapi->get_Attachments()->get_Count() - 1)->get_Properties()->get_Count());
mapi->get_Attachments()->idx_get(mapi->get_Attachments()->get_Count() - 1)->RemoveProperty(923467779);
// Delete anyone property
System::Console::WriteLine(System::String(L"After removal = ") + mapi->get_Attachments()->idx_get(mapi->get_Attachments()->get_Count() - 1)->get_Properties()->get_Count());
mapi->Save(L"EMAIL_589265.msg");
System::SharedPtr<MapiMessage> mapi2 = MapiMessage::FromFile(L"EMAIL_589265.msg");
System::Console::WriteLine(System::String(L"Reloaded = ") + mapi2->get_Attachments()->idx_get(mapi2->get_Attachments()->get_Count() - 1)->get_Properties()->get_Count());