기능 및 특성

특징 및 기능

이 페이지에서는 작동하는 C# 예제와 함께 Aspose.Email FOSS for .NET의 모든 주요 기능을 다룹니다.


MSG 파일 읽기

경로 또는 스트림에서 MSG 파일을 로드하고 모든 속성에 액세스합니다:

using System.IO;
using Aspose.Email.Foss.Msg;

using var stream = File.OpenRead("message.msg");
var message = MapiMessage.FromStream(stream);

Console.WriteLine(message.Subject);
Console.WriteLine(message.Body);
Console.WriteLine(message.HtmlBody);
Console.WriteLine(message.SenderName);
Console.WriteLine(message.SenderEmailAddress);
Console.WriteLine(message.MessageDeliveryTime);
Console.WriteLine(message.InternetMessageId);

비표준 MSG 파일을 관대하게 구문 분석하려면 strict: false를 사용하십시오:

var message = MapiMessage.FromFile("message.msg", strict: false);

ValidationIssues을 확인하여 포맷 경고를 검토하고 예외를 발생시키지 마세요:

foreach (var issue in message.ValidationIssues)
    Console.WriteLine($"Warning: {issue}");

MSG 파일 만들기

MapiMessage.Create()을 사용하여 전체 이메일을 작성하고 Save()으로 직렬화하십시오:

using System.IO;
using Aspose.Email.Foss.Msg;

var message = MapiMessage.Create("Hello", "Body");
message.SenderName = "Alice";
message.SenderEmailAddress = "alice@example.com";
message.HtmlBody = "<p>Body</p>";
message.InternetMessageId = "<hello@example.com>";
message.MessageDeliveryTime = new DateTime(2024, 1, 2, 3, 4, 5, DateTimeKind.Utc);

message.AddRecipient("bob@example.com", "Bob");

using var output = File.Create("hello.msg");
message.Save(output);

Save()은 인수가 없을 때 byte[]을 반환합니다. Save(path)은 파일 경로에 직접 씁니다.


수신자

To, CcBcc 수신자를 AddRecipient()와 함께 추가합니다:

message.AddRecipient("alice@example.com", "Alice");
message.AddRecipient("bob@example.com", "Bob", MapiMessage.RecipientTypeCc);
message.AddRecipient("carol@example.com", "Carol", MapiMessage.RecipientTypeBcc);

로드된 메시지에서 수신자 반복:

foreach (var recipient in message.Recipients)
    Console.WriteLine($"{recipient.DisplayName} <{recipient.EmailAddress}>");

첨부 파일

메타데이터와 함께 파일 또는 스트림 첨부 파일 추가:

// From byte array
message.AddAttachment("report.pdf", pdfBytes, "application/pdf");

// From stream
using var attachStream = File.OpenRead("photo.png");
message.AddAttachment("photo.png", attachStream, "image/png");

// Inline image with Content-ID
message.AddAttachment("logo.png", logoBytes, "image/png", contentId: "logo@cid");

로드된 메시지에서 첨부 파일 읽기:

foreach (var attachment in message.Attachments)
{
    Console.WriteLine($"Filename: {attachment.Filename}");
    Console.WriteLine($"MIME type: {attachment.MimeType}");
    Console.WriteLine($"Size: {attachment.Data.Length} bytes");
    File.WriteAllBytes(attachment.Filename!, attachment.Data);
}

임베디드 메시지 첨부 파일

다른 하나 안에 MapiMessage을 첨부하세요 — 전달된 이메일 체인에서 흔히 발생합니다:

using Aspose.Email.Foss.Msg;

var parent = MapiMessage.Create("Outer", "Parent body");
var child = MapiMessage.Create("Inner", "Child body");
child.SenderEmailAddress = "inner@example.com";
parent.AddEmbeddedMessageAttachment(child, "inner.msg");

parent.Save("outer.msg");

첨부된 메시지 읽기:

var loaded = MapiMessage.FromFile("outer.msg");
foreach (var attachment in loaded.Attachments)
{
    if (attachment.IsEmbeddedMessage)
    {
        Console.WriteLine($"Embedded: {attachment.EmbeddedMessage!.Subject}");
    }
}

EML 및 MIME 변환

RFC 5322 .eml 파일을 Outlook 호환 저장을 위한 MapiMessage에 로드합니다:

using System.IO;
using Aspose.Email.Foss.Msg;

using var input = File.OpenRead("message.eml");
var message = MapiMessage.LoadFromEml(input);

using var msgOutput = File.Create("message.msg");
message.Save(msgOutput);

MSG 파일에서 EML로 다시 변환:

var message = MapiMessage.FromFile("message.msg");
using var emlOutput = File.Create("roundtrip.eml");
message.SaveToEml(emlOutput);

LoadFromEml()string 경로나 byte[]도 허용합니다. SaveToEml()를 인수 없이 호출하면 byte[]를 반환합니다. 제목, 본문, HTML 본문, 발신자, 수신자 및 모든 첨부 파일(Content-ID가 포함된 인라인 이미지 포함)은 전체 EML ↔ MSG 라운드 트립 동안 보존됩니다.


MAPI 속성 액세스

MapiPropertyCollectionSetProperty()GetPropertyValue()을 통해 MAPI 속성에 대한 형식화된 액세스를 제공합니다. 표준 속성에는 CommonMessagePropertyId 열거형 값을 사용하십시오:

using Aspose.Email.Foss.Msg;

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

// Named convenience properties
Console.WriteLine(message.Subject);
Console.WriteLine(message.SenderName);
Console.WriteLine(message.MessageDeliveryTime);

// Iterate all MAPI property keys
foreach (var key in message.IterPropertyKeys())
    Console.WriteLine($"0x{(ushort)key.PropertyId:X4} / {key.PropertyType}");

CFB 컨테이너 액세스

Outlook MSG 파일은 Compound File Binary (CFB) 형식을 기반으로 합니다. CfbReader는 검사 및 데이터 추출을 위해 전체 디렉터리 트리를 노출합니다:

using System.Text;
using Aspose.Email.Foss.Cfb;

using var reader = CfbReader.FromFile("message.msg");

// Iterate all top-level children
foreach (var entry in reader.IterChildren(CfbConstants.RootStreamId))
    Console.WriteLine($"{(entry.IsStorage() ? "Storage" : "Stream")}: {entry.Name}");

// Navigate to a specific stream by path
var entry2 = reader.ResolvePath(["__substg1.0_0037001E"]);
if (entry2 is not null)
{
    var data = reader.GetStreamData(entry2.StreamId);
    Console.WriteLine(Encoding.Unicode.GetString(data));
}

CfbWriter를 사용하여 처음부터 CFB 문서를 만들고 직렬화하기:

using System.Text;
using Aspose.Email.Foss.Cfb;

var document = new CfbDocument();
document.Root.AddStream(new CfbStream("Notes", Encoding.UTF8.GetBytes("hello")));
var storage = document.Root.AddStorage(new CfbStorage("DataStore"));
storage.AddStream(new CfbStream("Payload", Encoding.UTF8.GetBytes("content")));

byte[] bytes = CfbWriter.ToBytes(document);
File.WriteAllBytes("output.cfb", bytes);

팁 및 모범 사례

  • using 또는 Dispose()MapiMessageCfbReader에 사용하여 파일 핸들을 해제합니다
  • 로드 후 message.ValidationIssues를 확인하여 비표준 MSG 형식을 감지합니다
  • FromFile() / FromStream()strict 매개변수는 오류 허용 범위를 제어합니다 — 서드파티 시스템에서 온 파일을 관대하게 파싱하려면 strict: false를 사용하십시오
  • MapiMessage.Create()은 기본적으로 유니코드 문자열 메시지를 생성합니다; 레거시 ANSI 호환성을 위해 unicodeStrings: false을 설정하십시오
  • 인수를 제공하지 않은 SaveToEml()byte[]을 반환합니다 — 인메모리 워크플로에 편리합니다

일반적인 문제

문제원인해결
CfbException 로드 시유효한 CFB/MSG 파일이 아님파일이 Outlook MSG인지 확인하십시오
로드 후 Body가 비어 있음본문이 HTML에만 저장됨대신 message.HtmlBody를 확인하십시오
수신자 유형 상수가 없음독립형 유형이 아님MapiMessage.RecipientTypeTo, MapiMessage.RecipientTypeCc 또는 MapiMessage.RecipientTypeBcc를 사용하십시오
LoadFromEml 후 첨부 파일이 0개EML에 Content-Disposition: attachment 파트가 없음인라인 파트(Content-ID만 해당)도 Attachments에 나타납니다

API 참조 요약

ClassDescription
MapiMessage고수준 MSG 메시지 표현
MapiAttachmentMapiMessage에 대한 첨부 파일 또는 포함된 메시지
MapiRecipientMapiMessage의 수신자
MapiProperty단일 MAPI 속성 항목
MapiPropertyCollection형식이 지정된 MAPI 속성 가방
CommonMessagePropertyId표준 MAPI 속성 식별자의 열거형
MsgReader저수준 MSG 구조 리더
MsgWriter저수준 MSG 구조 라이터
CfbReaderCFB 바이너리 컨테이너 리더
CfbWriterCFB 바이너리 컨테이너 라이터
CfbDocument구축을 위한 메모리 내 CFB 문서
CfbStorageCFB 문서의 스토리지 노드
CfbStreamCFB 문서의 스트림 노드
 한국어