Свойства MAPI

Свойства MAPI

Каждый файл MSG хранит данные в виде свойств MAPI — помеченных пар «ключ‑значение», идентифицируемых по идентификатору свойства и коду типа. Aspose.Email FOSS for .NET предоставляет прямой доступ к этим свойствам через MapiMessage, MapiPropertyCollection и перечисление CommonMessagePropertyId.


Чтение свойств

Удобные свойства

MapiMessage раскрывает наиболее часто используемые свойства как типизированные свойства C#:

using Aspose.Email.Foss.Msg;

using var message = MapiMessage.FromFile("sample.msg");

Console.WriteLine(message.Subject);              // string?
Console.WriteLine(message.Body);                 // string?
Console.WriteLine(message.HtmlBody);             // string?
Console.WriteLine(message.SenderName);           // string?
Console.WriteLine(message.SenderEmailAddress);   // string?
Console.WriteLine(message.InternetMessageId);    // string?
Console.WriteLine(message.MessageDeliveryTime);  // DateTime?
Console.WriteLine(message.MessageClass);         // string?

Прямой доступ к свойствам

Для свойств, не представленных в виде удобных полей, используйте GetPropertyValue:

// Read a string property by ID and type
var displayTo = message.GetPropertyValue(
    (ushort)CommonMessagePropertyId.DisplayTo,
    (ushort)PropertyTypeCode.PtypString,
    decode: true);

Console.WriteLine($"Display To: {displayTo}");

Перебрать все свойства

// List all property keys (ID + type pairs)
foreach (var key in message.IterPropertyKeys())
    Console.WriteLine($"Property: 0x{key:X8}");

// Iterate full property objects
foreach (var prop in message.IterProperties())
{
    Console.WriteLine($"ID=0x{prop.PropertyId:X4} " +
                      $"Type=0x{prop.PropertyType:X4} " +
                      $"Tag=0x{prop.PropertyTag:X8} " +
                      $"Value={prop.Value}");
}

Запись свойств

Установить свойства нового сообщения

var message = MapiMessage.Create("Test", "Body");

message.SetProperty(
    (ushort)CommonMessagePropertyId.SenderName,
    (ushort)PropertyTypeCode.PtypString,
    "Alice");

message.SetProperty(
    (ushort)CommonMessagePropertyId.SenderEmailAddress,
    (ushort)PropertyTypeCode.PtypString,
    "alice@example.com");

message.SetProperty(
    (ushort)CommonMessagePropertyId.MessageDeliveryTime,
    (ushort)PropertyTypeCode.PtypTime,
    new DateTime(2026, 3, 15, 10, 30, 0, DateTimeKind.Utc));

Прямой доступ к коллекции

MapiPropertyCollection предоставляет Add, Set, Get и Remove:

// Access the property collection
var props = message.Properties;

// Add a property
props.Add(
    (ushort)CommonMessagePropertyId.InternetCodepage,
    (ushort)PropertyTypeCode.PtypInteger32,
    65001,  // UTF-8
    flags: 0);

// Read it back
var codepage = props.Get(
    (ushort)CommonMessagePropertyId.InternetCodepage,
    (ushort)PropertyTypeCode.PtypInteger32);

Console.WriteLine($"Codepage: {codepage?.Value}");

// Remove a property
props.Remove(
    (ushort)CommonMessagePropertyId.InternetCodepage,
    (ushort)PropertyTypeCode.PtypInteger32);

Общие идентификаторы свойств

Перечисление CommonMessagePropertyId предоставляет именованные константы для часто используемых идентификаторов свойств MAPI:

PropertyDescription
SubjectТема сообщения
BodyТекстовое тело
BodyHtmlТело в формате HTML
SenderNameОтображаемое имя отправителя
SenderEmailAddressАдрес электронной почты отправителя
DisplayToСтрока отображения получателей (Кому)
DisplayCcСтрока отображения получателей в копии (Cc)
DisplayBccСтрока отображения получателей в скрытой копии (Bcc)
InternetMessageIdRFC 5322 Message-ID
MessageDeliveryTimeВременная метка доставки
TransportMessageHeadersНеобработанные заголовки RFC 5322
AttachFilenameКраткое имя файла вложения
AttachLongFilenameДлинное имя файла вложения
AttachMimeTagMIME-тип вложения
AttachContentIdContent-ID вложения

Коды типов недвижимости

Перечисление PropertyTypeCode сопоставляет коды типов MAPI:

ТипОписание
PtypStringUnicode-строка
PtypString8ANSI-строка
PtypInteger3232‑битное целое
PtypInteger6464‑битное целое
PtypBooleanBoolean
PtypTimeDateTime (FILETIME)
PtypBinaryМассив байтов
PtypGuidGUID

Свойства вложения

У каждого MapiAttachment также есть собственная коллекция Properties:

foreach (var attachment in message.Attachments)
{
    Console.WriteLine($"Attachment: {attachment.Filename}");

    foreach (var prop in attachment.Properties.IterProperties())
        Console.WriteLine($"  0x{prop.PropertyTag:X8} = {prop.Value}");
}

См. также

  • Reading MSG Files — Загрузка и просмотр MSG‑файлов
  • EML Conversion — Конвертация между форматами
  • CFB Containers — Доступ к низкоуровневым бинарным контейнерам
 Русский