Outlook MAPI 속성 액세스 및 관리

MAPI properties는 Microsoft Outlook 메시지에서 사용되는 메타데이터 항목으로, 발신자, 수신자, 제목, 첨부 파일 및 사용자 정의 데이터와 같은 속성을 정의합니다.

**Aspose.Email for C++**은 개발자가 프로그래밍 방식으로 이러한 속성에 접근, 수정 및 제거할 수 있도록 합니다. MapiMessage 객체, 첨부 파일 및 명명된 속성.

다음은 MapiProperty 클래스는 다음을 포함하는 MAPI 속성을 나타냅니다:

  • Name – 속성의 문자열 식별자입니다.
  • Tag – 속성을 참조하는 데 사용되는 숫자 식별자입니다.
  • Data – 속성 값을 나타내는 바이트 배열입니다.

이 문서의 샘플은 다음 헤더와 네임스페이스를 사용합니다:

#include <Mapi/MapiMessage.h>
#include <Mapi/MapiMessageFlags.h>
#include <Mapi/BodyContentType.h>
#include <Mapi/MapiProperty.h>
#include <Mapi/MapiPropertyContainer.h>
#include <Mapi/MapiNamedProperty.h>
#include <Mapi/MapiNamedPropertyMappingStorage.h>
#include <Mapi/MapiPropertyCollection.h>
#include <Mapi/MapiPropertyTag.h>
#include <Mapi/MapiPropertyType.h>
#include <Mapi/MapiRecipient.h>
#include <Mapi/MapiRecipientCollection.h>
#include <Mapi/MapiAttachment.h>
#include <Mapi/MapiAttachmentCollection.h>
#include <system/bit_converter.h>
#include <system/convert.h>
#include <system/guid.h>
#include <system/text/encoding.h>

using namespace System;
using namespace Aspose::Email::Mapi;

MAPI 속성 읽기

메시지의 모든 속성은 get_Properties, 태그별로 인덱싱됩니다; 그 MapiPropertyTag 클래스는 표준 태그에 이름을 붙입니다. 메시지에 없는 태그를 조회하면 nullptr.

많은 텍스트 속성이 두 가지 형태로 존재합니다 - 예를 들어 ANSI 태그인 PR_SUBJECT 및 유니코드 버전인 PR_SUBJECT_W - 그리고 메시지는 저장 형식에 따라 하나를 보유합니다. 샘플은 두 경우 모두 시도합니다. A MapiProperty 그런 다음 다음과 같은 메서드로 원시 데이터를 변환합니다 GetString 또는 GetInt32.

SharedPtr<MapiMessage> msg = MapiMessage::Load(u"Message.msg");

SharedPtr<MapiProperty> prop = msg->get_Properties()->idx_get(MapiPropertyTag::PR_SUBJECT);
if (prop == nullptr)
{
    // the Unicode counterpart of PR_SUBJECT
    prop = msg->get_Properties()->idx_get(MapiPropertyTag::PR_SUBJECT_W);
}

if (prop != nullptr)
{
    Console::WriteLine(u"Subject: " + prop->GetString());
}

// the code page of the internet message the item was created from
SharedPtr<MapiProperty> codePage = msg->get_Properties()->idx_get(MapiPropertyTag::PR_INTERNET_CPID);
if (codePage != nullptr)
{
    Console::WriteLine(u"Code page: " + Convert::ToString(codePage->GetInt32()));
}

MAPI 속성 설정

속성은 다음을 사용하여 추가하거나 교체합니다 SetProperty, 이는 MapiProperty 태그와 값의 원시 바이트로 구성됩니다. 문자열은 Unicode(UTF-16)로 저장됩니다 (_W) 태그이며, 날짜는 FILETIME으로 저장됩니다 - 1601년 1월 1일(UTC) 이후 100나노초 간격 수 - 이것은 DateTime::ToFileTimeUtc 생성합니다. 수신자는 자체 속성을 가지고 있으며, 이는 MapiRecipient.

C++에서는, MapiMessage 선언합니다 SetProperty 자신만의 오버로드가 있으며, 이는 기본 클래스의 일반 오버로드를 가립니다 MapiPropertyContainer. 따라서 샘플은 이를 통해 호출합니다 MapiPropertyContainer 메시지에 대한 포인터.

샘플은 새 메시지의 수신자를 팩스 주소로 바꾸고, 현재 사용자가 보낸 아직 전송되지 않은 메시지로 표시하며, 수정 시간을 설정합니다.

SharedPtr<MapiMessage> mapiMsg = MakeObject<MapiMessage>(u"user1@gmail.com", u"user2@gmail.com", u"This is subject", u"This is body");

// the general SetProperty overload is declared on the base class
SharedPtr<MapiPropertyContainer> container = mapiMsg;
container->SetProperty(MakeObject<MapiProperty>(MapiPropertyTag::PR_SENDER_ADDRTYPE_W, Text::Encoding::get_Unicode()->GetBytes(u"EX")));

// properties of a recipient
SharedPtr<MapiRecipient> recipientTo = mapiMsg->get_Recipients()->idx_get(0);
recipientTo->SetProperty(MakeObject<MapiProperty>(MapiPropertyTag::PR_RECEIVED_BY_ADDRTYPE_W, Text::Encoding::get_Unicode()->GetBytes(u"MYFAX")));
recipientTo->SetProperty(MakeObject<MapiProperty>(MapiPropertyTag::PR_RECEIVED_BY_EMAIL_ADDRESS_W,
    Text::Encoding::get_Unicode()->GetBytes(u"My Fax User@/FN=fax#/VN=voice#/CO=My Company/CI=Local")));

mapiMsg->SetMessageFlags(MapiMessageFlags::MSGFLAG_UNSENT | MapiMessageFlags::MSGFLAG_FROMME);
container->SetProperty(MakeObject<MapiProperty>(MapiPropertyTag::PR_RTF_IN_SYNC, BitConverter::GetBytes(static_cast<int64_t>(1))));

// a date property holds a FILETIME value
DateTime modified(2013, 9, 11, 0, 0, 0, DateTimeKind::Utc);
container->SetProperty(MakeObject<MapiProperty>(MapiPropertyTag::PR_LAST_MODIFICATION_TIME, BitConverter::GetBytes(modified.ToFileTimeUtc())));

mapiMsg->Save(u"MapiProperties.msg");

SharedPtr<MapiMessage> saved = MapiMessage::Load(u"MapiProperties.msg");
Console::WriteLine(u"Sender address type: " + saved->get_Properties()->idx_get(MapiPropertyTag::PR_SENDER_ADDRTYPE_W)->GetString());
Console::WriteLine(u"Modification time: " + saved->get_Properties()->idx_get(MapiPropertyTag::PR_LAST_MODIFICATION_TIME)->GetDateTime().ToString());

명명된 MAPI 속성 읽기

명명된 MAPI 속성은 사용자나 애플리케이션이 추가한 맞춤 속성입니다. 고정 태그 대신, 각각은 속성 집합 GUID와 이름 또는 숫자 식별자를 함께 사용해 식별되므로 서로 다른 애플리케이션의 속성이 충돌하지 않습니다. 속성이 메시지에 추가될 때 할당되는 태그에 저장됩니다.

Aspose.Email은 메시지와 첨부 파일에서 이러한 속성을 읽을 수 있도록 합니다.

MSG 파일에서 명명된 MAPI 속성 읽기

get_NamedProperties 메시지의 명명된 속성을 반환합니다. 컬렉션의 각 값은 MapiNamedProperty, 그 중 get_NameId 속성이 생성될 때 사용된 이름을 반환합니다.

읽을 것이 필요하므로 샘플은 먼저 두 개의 명명된 속성을 저장합니다. 명명된 속성은 세 단계에 걸쳐 생성됩니다: GetNextAvailablePropertyId 메시지의 NamedPropertyMapping 값 형식에 대한 자유 태그를 제공합니다, AddNamedPropertyMapping 그 태그를 이름 및 속성 집합 GUID에 바인딩하고, SetProperty 값을 저장합니다.

// the property set the custom properties belong to
Guid propertySet = Guid(u"6ED8DA90-450B-101B-98DA-00AA003F1305");

SharedPtr<MapiMessage> source = MakeObject<MapiMessage>(u"from@domain.com", u"to@domain.com", u"Named properties", u"Body");
SharedPtr<MapiPropertyContainer> container = source;

for (String name : { String(u"TEST"), String(u"MYPROP") })
{
    SharedPtr<MapiProperty> property = MakeObject<MapiProperty>(
        source->get_NamedPropertyMapping()->GetNextAvailablePropertyId(MapiPropertyType::PT_UNICODE),
        Text::Encoding::get_Unicode()->GetBytes(u"value of " + name));
    source->get_NamedPropertyMapping()->AddNamedPropertyMapping(property, name, propertySet);
    container->SetProperty(property);
}
source->Save(u"NamedProperties.msg");

// read the named properties back
SharedPtr<MapiMessage> message = MapiMessage::Load(u"NamedProperties.msg");
for (auto entry : message->get_NamedProperties())
{
    // DynamicCast_noexcept gives nullptr for a value that is not a named property
    SharedPtr<MapiNamedProperty> namedProperty = DynamicCast_noexcept<MapiNamedProperty>(entry.get_Value());
    if (namedProperty == nullptr)
    {
        continue;
    }

    String name = namedProperty->get_NameId();
    if (name == u"TEST" || name == u"MYPROP")
    {
        Console::WriteLine(name + u" = " + namedProperty->GetString());
    }
}

첨부 파일에서 명명된 MAPI 속성에 접근하기

첨부 파일에도 명명된 속성이 있습니다 - 애플리케이션은 예를 들어 자체 식별자로 모든 첨부 파일에 태그를 달 수 있습니다. 메시지와 그 첨부 파일의 모든 명명된 속성 이름은 메시지 매핑에 보관되며, 따라서 해당 속성이 거기에 등록되고 MapiAttachment. The get_NamedProperties 첨부 파일 컬렉션이 이를 반환합니다.

Guid propertySet = Guid(u"6ED8DA90-450B-101B-98DA-00AA003F1305");

SharedPtr<MapiMessage> source = MakeObject<MapiMessage>(u"from@domain.com", u"to@domain.com", u"Attachment properties", u"Body");
source->get_Attachments()->Add(u"report.txt", Text::Encoding::get_UTF8()->GetBytes(u"Report text"));

SharedPtr<MapiProperty> property = MakeObject<MapiProperty>(
    source->get_NamedPropertyMapping()->GetNextAvailablePropertyId(MapiPropertyType::PT_UNICODE),
    Text::Encoding::get_Unicode()->GetBytes(u"{1B2C3D4E-0000-0000-0000-000000000001}"));
source->get_NamedPropertyMapping()->AddNamedPropertyMapping(property, String(u"CustomAttGuid"), propertySet);
source->get_Attachments()->idx_get(0)->SetProperty(property);
source->Save(u"AttachmentNamedProperty.msg");

SharedPtr<MapiMessage> mapi = MapiMessage::Load(u"AttachmentNamedProperty.msg");
for (auto entry : mapi->get_Attachments()->idx_get(0)->get_NamedProperties())
{
    SharedPtr<MapiNamedProperty> namedProperty = DynamicCast_noexcept<MapiNamedProperty>(entry.get_Value());
    if (namedProperty != nullptr && String::Compare(namedProperty->get_NameId(), u"CustomAttGuid", StringComparison::OrdinalIgnoreCase) == 0)
    {
        Console::WriteLine(u"CustomAttGuid = " + namedProperty->GetString());
    }
}

MAPI 속성 제거

RemoveProperty 태그로 속성을 삭제합니다 - 메시지와 첨부 파일 또는 수신자 모두에서. 샘플은 Outlook 메시지를 새 메시지에 첨부하고, PR_RENDERING_POSITION 첨부 파일의 해당 속성을 확인하고 저장 후 다시 로드했을 때 해당 속성이 제거된 상태를 유지하는지 검증합니다. 저장 시 다른 속성이 첨부 파일에 추가될 수 있으므로, 검사에서는 속성 수가 아니라 태그 자체를 확인합니다.

SharedPtr<MapiMessage> mapi = MakeObject<MapiMessage>(u"from@domain.com", u"to@domain.com", u"subject", u"body");
mapi->SetBodyContent(u"<html><body><h1>This is the body content</h1></body></html>", BodyContentType::Html);
mapi->get_Attachments()->Add(u"Attached message.msg", MapiMessage::Load(u"Message.msg"));

SharedPtr<MapiAttachment> attachment = mapi->get_Attachments()->idx_get(mapi->get_Attachments()->get_Count() - 1);
Console::WriteLine(u"Before removal: " + Convert::ToString(attachment->get_Properties()->ContainsKey(MapiPropertyTag::PR_RENDERING_POSITION)));

attachment->RemoveProperty(MapiPropertyTag::PR_RENDERING_POSITION);
Console::WriteLine(u"After removal: " + Convert::ToString(attachment->get_Properties()->ContainsKey(MapiPropertyTag::PR_RENDERING_POSITION)));

mapi->Save(u"PropertyRemoved.msg");

SharedPtr<MapiMessage> reloaded = MapiMessage::Load(u"PropertyRemoved.msg");
SharedPtr<MapiAttachment> reloadedAttachment = reloaded->get_Attachments()->idx_get(reloaded->get_Attachments()->get_Count() - 1);
Console::WriteLine(u"After reloading: " + Convert::ToString(reloadedAttachment->get_Properties()->ContainsKey(MapiPropertyTag::PR_RENDERING_POSITION)));