Xử lý Tệp Đính Kèm TNEF trong Tin Nhắn Email

TNEF (Transport Neutral Encapsulation Format) là một định dạng độc quyền được Microsoft Outlook sử dụng để đóng gói nội dung phong phú trong tệp đính kèm - thường được lưu dưới dạng winmail.dat. API Aspose.Email cho phép bạn đọc các tin nhắn email có tệp đính kèm TNEF và chỉnh sửa nội dung của tệp đính kèm. Email sau đó có thể được lưu dưới dạng email thông thường hoặc cùng định dạng, giữ nguyên các tệp đính kèm TNEF. Bài viết này trình bày các mẫu mã khác nhau để làm việc với các tin nhắn chứa tệp đính kèm TNEF. Bài viết cũng chỉ cách tạo tệp EML TNEF từ các tệp MSG của Outlook.

Đọc Tin Nhắn có Tệp Đính Kèm TNEF

Đoạn mã dưới đây cho bạn thấy cách đọc một tin nhắn giữ nguyên các tệp đính kèm TNEF.

// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();

MsgLoadOptions options = new MsgLoadOptions();
options.PreserveTnefAttachments = true;
MailMessage eml = MailMessage.Load(dataDir + "EmbeddedImage1.msg", options);
foreach (Attachment attachment in eml.Attachments)
{
    Console.WriteLine(attachment.Name);
}

Đọc Tin Nhắn không có Tệp Đính Kèm TNEF

Đoạn mã sau cho bạn thấy cách đọc một tin nhắn mà không giữ lại các tệp đính kèm TNEF. Thiết lập PreserveTnefAttachments đặt false là hành vi mặc định: container TNEF được giải mã và nội dung của nó được hiển thị như các tệp đính kèm thông thường thay vì một tệp winmail.dat duy nhất.

// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();

MsgLoadOptions options = new MsgLoadOptions();
options.PreserveTnefAttachments = false;
MailMessage eml = MailMessage.Load(dataDir + "EmbeddedImage1.msg", options);
foreach (Attachment attachment in eml.Attachments)
{
    Console.WriteLine(attachment.Name);
}

Tải và Lưu Tệp Đính Kèm TNEF

Với Aspose.Email cho .NET, bạn có thể tải các tệp đính kèm TNEF trực tiếp vào một MapiAttachment đối tượng sử dụng đường dẫn tệp hoặc luồng, và sau đó lưu đối tượng dưới định dạng TNEF. Điều này cho phép tạo các tệp winmail.dat hoặc bảo tồn định dạng đặc thù của Outlook trong quy trình công việc email.

API cung cấp các thành viên sau trong MapiAttachment lớp:

Tải Tệp Đính Kèm TNEF

Lưu Tệp Đính Kèm TNEF

Mẫu mã dưới đây minh họa cách trích xuất tệp đính kèm winmail.dat từ một tin nhắn email, giữ nguyên nó và thêm lại như một tệp đính kèm vào tin nhắn:

// message.eml contains a winmail.dat attachment, but by default, the attachment is not preserved.
var msg = MapiMessage.Load("message.eml");

// Save the attachment to TNEF format in a stream and load it back
var ms = new MemoryStream();
msg.Attachments[0].SaveToTnef(ms);

ms.Position = 0;
var fromTnefAttachment = MapiAttachment.LoadFromTnef(ms);
msg.Attachments.Add(fromTnefAttachment);

// The same can be done through a file
msg.Attachments[0].SaveToTnef("winmail.dat");

fromTnefAttachment = MapiAttachment.LoadFromTnef("winmail.dat");
msg.Attachments.Add(fromTnefAttachment);

Cập Nhật Tài Nguyên trong Tệp Đính Kèm TNEF

Đoạn mã dưới đây cho bạn thấy cách cập nhật các tài nguyên trong một tệp đính kèm TNEF và giữ nguyên định dạng TNEF.

public static void TestUpdateResources(string dataDir)
{
    string fileName = dataDir + "tnefEML1.eml";
    string imgFileName = dataDir + "Untitled.jpg";
    string outFileName = dataDir + "UpdateTNEFAttachments_out.eml";
    MailMessage originalMailMessage = MailMessage.Load(fileName);
    UpdateResources(originalMailMessage, imgFileName);
    EmlSaveOptions emlSo = new EmlSaveOptions(MailMessageSaveType.EmlFormat);
    emlSo.FileCompatibilityMode = FileCompatibilityMode.PreserveTnefAttachments;
    originalMailMessage.Save(outFileName, emlSo);
}

private static void UpdateResources(MailMessage msg, string imgFileName)
{
    for (int i = 0; i < msg.Attachments.Count; i++)
    {
        if ((msg.Attachments[i].ContentType.MediaType == "image/png") || (msg.Attachments[i].ContentType.MediaType == "application/octet-stream" && Path.GetExtension(msg.Attachments[i].ContentType.Name) == ".jpg"))
        {
            msg.Attachments[i].ContentStream = new MemoryStream(File.ReadAllBytes(imgFileName));
        }
        else if ((msg.Attachments[i].ContentType.MediaType == "message/rfc822") || (msg.Attachments[i].ContentType.MediaType == "application/octet-stream" && Path.GetExtension(msg.Attachments[i].ContentType.Name) == ".msg"))
        {
            MemoryStream ms = new MemoryStream();
            msg.Attachments[i].Save(ms);
            ms.Position = 0;
            MailMessage embeddedMessage = MailMessage.Load(ms);
            UpdateResources(embeddedMessage, imgFileName);
            MemoryStream msProcessedEmbedded = new MemoryStream();
            embeddedMessage.Save(msProcessedEmbedded, SaveOptions.DefaultMsgUnicode);
            msProcessedEmbedded.Position = 0;
            msg.Attachments[i].ContentStream = msProcessedEmbedded;
        }
    }

    foreach (LinkedResource att in msg.LinkedResources)
    {
        if (att.ContentType.MediaType == "image/png")
            att.ContentStream = new MemoryStream(File.ReadAllBytes(imgFileName));
    }
}

Thêm Tệp Đính Kèm vào Tin Nhắn TNEF

Đoạn mã dưới đây cho bạn thấy cách thêm các tệp đính kèm mới vào tin nhắn chính chứa TNEF.


string fileName = "MainMessage.eml";
string attachName = "s.png";
string outFileName = "test.eml";

MailMessage mailMessage = MailMessage.Load(fileName);
mailMessage.Attachments.Add(new Attachment(File.OpenRead(attachName), "s.png", "image/png"));

// The TNEF content of the original message is preserved via EmlSaveOptions
EmlSaveOptions emlSaveOptions = new EmlSaveOptions(MailMessageSaveType.EmlFormat)
{
    FileCompatibilityMode = FileCompatibilityMode.PreserveTnefAttachments
};
mailMessage.Save(outFileName, emlSaveOptions);

Tạo TNEF EML từ MSG

Các tệp MSG của Outlook đôi khi chứa thông tin như bảng và kiểu văn bản có thể bị thay đổi nếu chuyển đổi sang EML. Tạo tin nhắn TNEF từ các tệp MSG như vậy cho phép giữ nguyên định dạng và thậm chí gửi các tin nhắn này qua các client email mà vẫn giữ định dạng. The MailConversionOptions.ConvertAsTnef thuộc tính được sử dụng để đạt được điều này. Đoạn mã dưới đây cho bạn thấy cách tạo EML TNEF từ MSG.

MapiMessage mapiMsg = MapiMessage.FromFile(dataDir + "Message.msg");

MailConversionOptions mco = new MailConversionOptions();

mco.ConvertAsTnef = true;

MailMessage message = mapiMsg.ToMailMessage(mco); 

Ngoài ra, một TNEF EML có thể được tạo bằng cách tải tệp MSG với PreserveTnefAttachments tùy chọn của MsgLoadOptions class được bật, và sau đó lưu kết quả dưới dạng EML.

// Loading the MSG with PreserveTnefAttachments will create the TNEF eml.
MsgLoadOptions options = new MsgLoadOptions();
options.PreserveTnefAttachments = true;

MailMessage eml = MailMessage.Load(msgFileName, options);
eml.Save(emlFileName, SaveOptions.DefaultEml);

Xác Định Tin Nhắn Định Dạng TNEF

Đoạn mã dưới đây cho bạn thấy cách phát hiện một tin nhắn có định dạng TNEF hay không.

MailMessage mail = MailMessage.Load(dataDir + "tnefEml1.eml");

bool isTnef = mail.OriginalIsTnef;

Console.WriteLine("Is input EML originally TNEF? {0}", isTnef.ToString());

Xác Định Tệp Đính Kèm Định Dạng TNEF

Cái Attachment.IsTnef thuộc tính cho phép phát hiện liệu tệp đính kèm tin nhắn có định dạng TNEF hay không.

var eml = MailMessage.Load(fileName);

foreach (var attachment in eml.Attachments)
{
    Console.WriteLine($"Is Attachment TNEF?: {attachment.IsTnef}");
}