Tính năng và Chức năng

Tính năng và Chức năng

Trang này bao phủ mọi tính năng chính của Aspose.Email FOSS for .NET với các ví dụ C# hoạt động.


Đọc tệp MSG

Tải tệp MSG từ đường dẫn hoặc luồng và truy cập tất cả các thuộc tính của nó:

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);

Sử dụng strict: false để phân tích cú pháp linh hoạt cho các tệp MSG không chuẩn:

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

Kiểm tra ValidationIssues để xem bất kỳ cảnh báo định dạng nào mà không gây ra lỗi:

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

Tạo các tệp MSG

Xây dựng một email hoàn chỉnh với MapiMessage.Create() và tuần tự hoá với 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() không có đối số trả về một byte[]. Save(path) ghi trực tiếp vào đường dẫn tệp.


Người nhận

Thêm các người nhận To, CcBcc với AddRecipient():

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

Lặp lại các người nhận từ một tin nhắn đã tải:

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

Tệp đính kèm

Thêm tệp hoặc luồng đính kèm kèm siêu dữ liệu:

// 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");

Đọc tệp đính kèm từ tin nhắn đã tải:

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);
}

Tệp đính kèm tin nhắn nhúng

Đính kèm một MapiMessage bên trong một cái khác — thường gặp trong chuỗi email được chuyển tiếp:

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");

Vui lòng cung cấp nội dung văn bản cần dịch.

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

Chuyển đổi EML và MIME

Tải tệp RFC 5322 .eml vào một MapiMessage để lưu trữ tương thích với Outlook:

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);

Chuyển lại sang EML từ tệp MSG:

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

LoadFromEml() cũng chấp nhận một đường dẫn string hoặc byte[]. SaveToEml() không có đối số trả về một byte[]. Chủ đề, nội dung, nội dung HTML, người gửi, người nhận và tất cả các tệp đính kèm (bao gồm cả hình ảnh nội tuyến với Content-ID) được giữ nguyên qua các vòng chuyển đổi đầy đủ EML ↔ MSG.


Truy cập thuộc tính MAPI

MapiPropertyCollection cung cấp quyền truy cập có kiểu vào các thuộc tính MAPI thông qua SetProperty()GetPropertyValue(). Sử dụng các giá trị enum CommonMessagePropertyId cho các thuộc tính tiêu chuẩn:

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}");

Truy cập Container CFB

Các tệp Outlook MSG được xây dựng trên định dạng Compound File Binary (CFB). CfbReader hiển thị toàn bộ cây thư mục để kiểm tra và trích xuất dữ liệu:

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));
}

Xây dựng và tuần tự hoá tài liệu CFB từ đầu với CfbWriter:

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);

Mẹo và Thực tiễn tốt nhất

  • Sử dụng using hoặc Dispose() trên MapiMessageCfbReader để giải phóng các tay cầm tệp
  • Kiểm tra message.ValidationIssues sau khi tải để phát hiện định dạng MSG không chuẩn
  • Tham số strict trong FromFile() / FromStream() kiểm soát độ chịu lỗi — sử dụng strict: false để phân tích lỏng lẻo các tệp từ hệ thống bên thứ ba
  • MapiMessage.Create() tạo ra các thông điệp dạng chuỗi Unicode theo mặc định; đặt unicodeStrings: false để tương thích với ANSI cũ
  • SaveToEml() không có đối số sẽ trả về byte[] — thuận tiện cho quy trình làm việc trong bộ nhớ

Các vấn đề thường gặp

IssueCauseFix
CfbException khi tảiKhông phải là tệp CFB/MSG hợp lệXác minh tệp là Outlook MSG
Body trống sau khi tảiNội dung chỉ được lưu dưới dạng HTMLThay vào đó, kiểm tra message.HtmlBody
Không tìm thấy hằng số loại người nhậnKhông phải là loại độc lậpSử dụng MapiMessage.RecipientTypeTo, MapiMessage.RecipientTypeCc hoặc MapiMessage.RecipientTypeBcc
0 tệp đính kèm sau LoadFromEmlEML không có phần Content-Disposition: attachmentCác phần nội tuyến (chỉ Content-ID) cũng xuất hiện trong Attachments

Tóm tắt Tham chiếu API

LớpMô tả
MapiMessageBiểu diễn tin nhắn MSG cấp cao
MapiAttachmentTệp đính kèm hoặc tin nhắn nhúng trên một MapiMessage
MapiRecipientNgười nhận trên một MapiMessage
MapiPropertyMục thuộc tính MAPI đơn
MapiPropertyCollectionBộ thuộc tính MAPI có kiểu
CommonMessagePropertyIdLiệt kê các định danh thuộc tính MAPI tiêu chuẩn
MsgReaderTrình đọc cấu trúc MSG cấp thấp
MsgWriterTrình ghi cấu trúc MSG cấp thấp
CfbReaderTrình đọc container nhị phân CFB
CfbWriterTrình ghi container nhị phân CFB
CfbDocumentTài liệu CFB trong bộ nhớ để xây dựng
CfbStorageNút lưu trữ trong tài liệu CFB
CfbStreamNút luồng trong tài liệu CFB
 Tiếng Việt