Làm việc với Tệp đính kèm và Đối tượng Nhúng

Làm việc với Tệp Đính Kèm

Tệp đính kèm email là các tệp được gửi cùng với tin nhắn email. Những tệp này có thể bao gồm tài liệu, hình ảnh, lưu trữ và hơn nữa.

Trong Aspose.Email cho C++, các tệp đính kèm được quản lý thông qua Attachment lớp, hoạt động chung với MailMessage class. Bạn có thể thêm, xóa, trích xuất hoặc hiển thị các tệp đính kèm bằng chương trình.

Lưu ý: Kích thước tối đa của tệp đính kèm phụ thuộc vào máy chủ email (ví dụ, Gmail giới hạn tệp đính kèm tới 10 MB).

Các mẫu trong bài viết này sử dụng các tiêu đề và không gian tên sau:

#include <MailMessage.h>
#include <MailAddress.h>
#include <MailAddressCollection.h>
#include <Attachment.h>
#include <AttachmentCollection.h>
#include <ReferenceAttachment.h>
#include <AttachmentProviderType.h>
#include <AttachmentPermissionType.h>
#include <AlternateView.h>
#include <AlternateViewCollection.h>
#include <LinkedResource.h>
#include <LinkedResourceCollection.h>
#include <EmlLoadOptions.h>
#include <SaveOptions.h>
#include <EmlSaveOptions.h>
#include <MsgSaveOptions.h>
#include <HtmlSaveOptions.h>
#include <ResourceHtmlRenderingEventArgs.h>
#include <Mime/MediaTypeNames.h>
#include <Mime/ContentType.h>
#include <Mime/HeaderCollection.h>
#include <system/io/file.h>
#include <system/io/directory.h>
#include <system/io/path.h>
#include <system/convert.h>

using namespace System;
using namespace Aspose::Email;
using namespace Aspose::Email::Mime;

Thêm Tệp Đính Kèm vào Email

Để đính kèm một hoặc nhiều tệp vào tin nhắn email, thực hiện các bước dưới đây:

  1. Tạo một đối tượng của MailMessage lớp.
  2. Create Attachment đối tượng cho mỗi tệp.
  3. Thêm các tệp đính kèm vào tin nhắn - qua Tệp Đính Kèm bộ sưu tập hoặc với AddAttachment.
  4. Lưu tin nhắn nếu cần.
SharedPtr<MailMessage> message = MakeObject<MailMessage>();
message->set_From(u"sender@sender.com");
message->get_To()->Add(u"receiver@gmail.com");
message->set_Subject(u"Files for the review");

// an Attachment is created from a file; its name and content type come from the file
message->get_Attachments()->Add(MakeObject<Attachment>(u"description.html"));
message->AddAttachment(MakeObject<Attachment>(u"1.jpg"));
message->AddAttachment(MakeObject<Attachment>(u"portrait.jpg"));

message->Save(u"WithAttachments.msg", SaveOptions::get_DefaultMsgUnicode());
Console::WriteLine(u"Attachments: " + Convert::ToString(message->get_Attachments()->get_Count()));

Xóa Tệp Đính Kèm khỏi Email

Bạn có thể dễ dàng xóa các tệp đính kèm khỏi tin nhắn bằng cách sử dụng Remove() phương thức của Tệp Đính Kèm bộ sưu tập.

Đoạn mã sau minh họa cách xóa một tệp đính kèm:

  1. Tải hoặc tạo một MailMessage thể hiện.
  2. Tìm tệp đính kèm cần xóa - giữ lại đối tượng bạn đã thêm, hoặc tìm nó trong bộ sưu tập.
  3. Truyền nó tới Remove(); RemoveAt() xóa tệp đính kèm ở một vị trí thay thế.
  4. Tùy chọn, hiển thị các tệp đính kèm còn lại.
SharedPtr<MailMessage> message = MakeObject<MailMessage>();
message->set_From(u"sender@sender.com");
message->get_To()->Add(u"receiver@gmail.com");

SharedPtr<Attachment> description = MakeObject<Attachment>(u"description.html");
message->get_Attachments()->Add(description);
message->AddAttachment(MakeObject<Attachment>(u"1.jpg"));
message->AddAttachment(MakeObject<Attachment>(u"portrait.jpg"));

// remove one attachment and save the message
message->get_Attachments()->Remove(description);
message->Save(u"AttachmentRemoved.msg", SaveOptions::get_DefaultMsgUnicode());

for (SharedPtr<Attachment> attachment : message->get_Attachments())
{
    Console::WriteLine(u"Left: " + attachment->get_Name());
}

Hiển Thị Tên Tệp Đính Kèm

Cái Tên của một tệp đính kèm là tên tệp mà tin nhắn đặt cho nó. Vòng lặp qua bộ sưu tập liệt kê tất cả:

SharedPtr<MailMessage> message = MailMessage::Load(u"WithAttachments.msg");

for (SharedPtr<Attachment> attachment : message->get_Attachments())
{
    Console::WriteLine(attachment->get_Name());
}

Trích Xuất Tệp Đính Kèm từ Email

Để trích xuất và lưu các tệp đính kèm từ một tệp email hiện có, thực hiện các bước dưới đây:

  1. Tải tin nhắn bằng cách sử dụng MailMessage lớp.
  2. Lặp qua Tệp Đính Kèm bộ sưu tập.
  3. Lưu mỗi tệp đính kèm vào đĩa với Attachment::Save và tùy chọn hiển thị tên của nó.

Đoạn mã sau lưu mọi tệp đính kèm của một tin nhắn vào một thư mục, mỗi tệp dưới tên riêng của nó:

SharedPtr<MailMessage> message = MailMessage::Load(u"WithAttachments.msg");

IO::Directory::CreateDirectory_(u"ExtractedAttachments");
for (SharedPtr<Attachment> attachment : message->get_Attachments())
{
    attachment->Save(IO::Path::Combine(u"ExtractedAttachments", attachment->get_Name()));
    Console::WriteLine(u"Saved " + attachment->get_Name());
}

|Tệp đính kèm đã được trích xuất trong email| | :- | |todo:image_alt_text|

Đọc Mô Tả Nội Dung Tệp Đính Kèm

Một tệp đính kèm mang các tiêu đề MIME riêng. Tiêu đề tùy chọn Content-Description chứa mô tả ngắn gọn của tệp; nó được đọc từ Headers bộ sưu tập của tệp đính kèm. Mẫu ghi tiêu đề và đọc lại từ tin nhắn đã lưu.

SharedPtr<MailMessage> source = MakeObject<MailMessage>(u"sender@sender.com", u"receiver@gmail.com", u"Report", u"See the attachment.");
SharedPtr<Attachment> report = MakeObject<Attachment>(u"description.html");
report->get_Headers()->Add(u"Content-Description", u"Quarterly report");
source->get_Attachments()->Add(report);
source->Save(u"WithDescription.eml", SaveOptions::get_DefaultEml());

SharedPtr<MailMessage> message = MailMessage::Load(u"WithDescription.eml");
String description = message->get_Attachments()->idx_get(0)->get_Headers()->Get(u"Content-Description");
Console::WriteLine(u"Content-Description: " + description);

Làm việc với các đối tượng nhúng

Một đối tượng nhúng là một tệp được tạo trong một ứng dụng và được chèn vào trong một tài liệu hoặc email khác. Ví dụ, một bảng tính Microsoft Excel có thể được nhúng trong tài liệu Word, hoặc một hình ảnh có thể được nhúng trực tiếp vào phần thân email.

Khi một đối tượng được nhúng (không chỉ đính kèm hoặc liên kết), nó giữ nguyên định dạng gốc và có thể được mở hoặc chỉnh sửa trong ứng dụng gốc.

Nhúng các đối tượng vào Email

Để nhúng hình ảnh hoặc đối tượng khác trong tin nhắn email, sử dụng LinkedResource lớp cùng với MailMessage và AlternateView các lớp. Điều này cho phép bạn chèn hình ảnh hoặc nội dung media nội tuyến trực tiếp trong phần thân tin nhắn.

Mẫu mã sau minh họa cách tạo một tin nhắn email có cả nội dung văn bản thuần và HTML, trong đó bao gồm một hình ảnh nhúng:

  1. Tạo một đối tượng của MailMessage lớp.
  2. Đặt các trường người gửi, người nhận và tiêu đề.
  3. Tạo phần thân văn bản thuần bằng cách sử dụng AlternateView.
  4. Tạo phần thân HTML chứa tham chiếu đến đối tượng nhúng bằng cách sử dụng cid (Content-ID). Viết tham chiếu trong dấu ngoặc kép, src="cid:barcode": ở dạng này, một chương trình tải tin nhắn sau này sẽ nhận diện hình ảnh là tài nguyên nhúng chứ không phải là tệp đính kèm.
  5. Tạo một đối tượng của LinkedResource lớp và tải đối tượng.
  6. Gán Content-ID cho tài nguyên liên kết.
  7. Thêm tài nguyên liên kết và các chế độ xem thay thế vào tin nhắn.
  8. Lưu hoặc gửi tin nhắn email.
SharedPtr<MailMessage> mail = MakeObject<MailMessage>();
mail->set_From(MakeObject<MailAddress>(u"test001@gmail.com"));
mail->get_To()->Add(u"test001@gmail.com");
mail->set_Subject(u"This is an email");

// the plain text part, for clients that do not display HTML
SharedPtr<AlternateView> plainView = AlternateView::CreateAlternateViewFromString(u"This is my plain text content", nullptr, u"text/plain");

// the HTML part refers to the image by its Content-ID: src="cid:barcode" maps to the resource with the ID "barcode"
SharedPtr<AlternateView> htmlView = AlternateView::CreateAlternateViewFromString(u"Here is an embedded image.<img src=\"cid:barcode\">", nullptr, u"text/html");

SharedPtr<LinkedResource> barcode = MakeObject<LinkedResource>(u"1.jpg", Mime::MediaTypeNames::Image::Jpeg);
barcode->set_ContentId(u"barcode");

mail->get_LinkedResources()->Add(barcode);
mail->get_AlternateViews()->Add(plainView);
mail->get_AlternateViews()->Add(htmlView);

mail->Save(u"EmbeddedImage.eml", SaveOptions::get_DefaultEml());

Lưu ý: > Bạn có thể nhúng nhiều đối tượng, nhưng kích thước tối đa của tin nhắn bị giới hạn bởi máy chủ email của bạn. Ví dụ, Gmail giới hạn kích thước tin nhắn tới 10 MB.

Trích Xuất Đối Tượng Nhúng từ Email

Bạn cũng có thể trích xuất các đối tượng nhúng, như hình ảnh, từ một tin nhắn email hiện có. Chúng không phải là tệp đính kèm: một tin nhắn đã tải sẽ liệt kê chúng trong LinkedResources bộ sưu tập. Quá trình này tương tự như trích xuất tệp đính kèm:

  1. Tải tệp email vào một MailMessage.
  2. Lặp qua các tài nguyên được liên kết.
  3. Lưu mỗi đối tượng nhúng vào đĩa; Content-ID của nó cho biết tham chiếu nào trong phần thân HTML nó thuộc về.
  4. Tùy chọn, hiển thị tên tệp trong console.
SharedPtr<MailMessage> message = MailMessage::Load(u"EmbeddedImage.eml");

IO::Directory::CreateDirectory_(u"EmbeddedObjects");
int32_t index = 0;
for (SharedPtr<LinkedResource> resource : message->get_LinkedResources())
{
    String fileName = IO::Path::Combine(u"EmbeddedObjects", u"object_" + Convert::ToString(index++) + u".jpg");
    resource->Save(fileName);
    Console::WriteLine(u"cid:" + resource->get_ContentId() + u" -> " + fileName);
}

|Các đối tượng nhúng đã trích xuất trong email| | :- | |todo:image_alt_text|

Thêm Cách làm với Tệp Đính kèm

Thêm một Tệp Đính Kèm Tham Chiếu

Một tệp đính kèm tham chiếu không đi kèm với tin nhắn: nó chứa một liên kết tới tệp trong vị trí chia sẻ, vì vậy người nhận luôn mở phiên bản hiện tại và tin nhắn vẫn giữ kích thước nhỏ. ReferenceAttachment nhận URI, trong khi ProviderType đặt tên dịch vụ lưu trữ và PermissionType các quyền truy cập mà người nhận nhận được.

SharedPtr<MailMessage> eml = MailMessage::Load(u"sample.eml");

// the message carries a link to the file, not the file itself
SharedPtr<ReferenceAttachment> refAttach = MakeObject<ReferenceAttachment>(u"https://example.com/shared/Document.docx");
refAttach->set_Name(u"Document.docx");
refAttach->set_ProviderType(AttachmentProviderType::OneDrivePro);
refAttach->set_PermissionType(AttachmentPermissionType::AnyoneCanEdit);

eml->get_Attachments()->Add(refAttach);
eml->Save(u"WithReferenceAttachment.eml", SaveOptions::get_DefaultEml());

// a reference attachment is recognized when the message is read back
SharedPtr<MailMessage> reloaded = MailMessage::Load(u"WithReferenceAttachment.eml");
for (SharedPtr<Attachment> attachment : reloaded->get_Attachments())
{
    Console::WriteLine(attachment->get_Name() + u" - IsUri: " + Convert::ToString(attachment->get_IsUri()));
}

Xác định Tin nhắn Nhúng và Nội dung Đã Ký

IsEmbeddedMessage cho biết liệu một tệp đính kèm có phải là một tin nhắn hay không; một tệp đính kèm như vậy có thể được phân tích bằng MailMessage::Load trực tiếp từ luồng nội dung của nó. Một tin nhắn đã ký là một trường hợp khác: nó gồm một smime.p7m phần, và IsSigned cùng với IsEncrypted báo cáo điều đó.

// an attachment that is itself a message
SharedPtr<MailMessage> eml = MailMessage::Load(u"WithEmbeddedMsg.msg");
for (SharedPtr<Attachment> attachment : eml->get_Attachments())
{
    Console::WriteLine(attachment->get_Name() + u": " +
        (attachment->get_IsEmbeddedMessage() ? u"an embedded message" : u"a regular attachment"));

    if (attachment->get_IsEmbeddedMessage())
    {
        // the attachment content is a complete message and can be parsed as one
        SharedPtr<MailMessage> inner = MailMessage::Load(attachment->get_ContentStream());
        Console::WriteLine(u"   subject of the embedded message: " + inner->get_Subject());
    }
}

// a signed message carries a single smime.p7m part
SharedPtr<MailMessage> signedEml = MailMessage::Load(u"signed.eml");
Console::WriteLine(u"IsSigned: " + Convert::ToString(signedEml->get_IsSigned()) +
    u", IsEncrypted: " + Convert::ToString(signedEml->get_IsEncrypted()));

for (SharedPtr<Attachment> attachment : signedEml->get_Attachments())
{
    Console::WriteLine(u"Signed email attachment: " + attachment->get_Name());
}

Hình ảnh nội dòng

Một hình ảnh nhúng không được liệt kê như một tệp đính kèm; nó là một LinkedResource của ContentId phần thân HTML tham chiếu tới thông qua một cid: URL.

Thêm Hình ảnh Nhúng vào Thân

Một hình ảnh được đặt trong thân bằng cách thêm nó vào LinkedResources với Content-ID và tham chiếu tới ID đó từ HTML - mẫu đầy đủ nằm trong Nhúng Đối tượng vào Email. Số lượng đối tượng nhúng chỉ bị giới hạn bởi kích thước tin nhắn mà máy chủ mail chấp nhận.

Xóa Hình ảnh Nhúng trong Thân

RemoveAt và Xóa cả hai đều nhận một cờ cũng xóa <img src=cid:...> tham chiếu từ HTML, vì vậy không để lại hình ảnh hỏng. Hãy nhớ rằng các chế độ xem thay thế giữ bản sao riêng của các tài nguyên.

SharedPtr<MailMessage> eml = MailMessage::Load(u"EmailWithAttachEmbedded.eml");

Console::WriteLine(u"Linked resources before: " + Convert::ToString(eml->get_LinkedResources()->get_Count()));

// true also removes the <img src=cid:...> reference from the HTML body
eml->get_LinkedResources()->RemoveAt(0, true);

// or drop every inline resource at once
eml->get_LinkedResources()->Clear(true);

// the alternate views hold their own copies of the resources
for (SharedPtr<AlternateView> view : eml->get_AlternateViews())
{
    view->get_LinkedResources()->Clear(true);
}

Console::WriteLine(u"Linked resources after: " + Convert::ToString(eml->get_LinkedResources()->get_Count()));
eml->Save(u"WithoutInlineImages.eml", SaveOptions::get_DefaultEml());

Trích xuất Hình ảnh Liên kết trong Thân HTML

Một số bản tin không nhúng hình ảnh của chúng - phần thân HTML trỏ tới chúng bằng các thẻ http liên kết, và tin nhắn sẽ bị hỏng khi các liên kết đó ngừng hoạt động. Thiết lập ExtractHTMLBodyResourcesAsAttachments làm cho thư viện tải các tài nguyên đó trong khi tin nhắn đang được xuất và nhúng chúng vào đầu ra. Các ResourceHtmlRendering sự kiện báo cáo mọi tài nguyên đã được xử lý.

SharedPtr<MailMessage> mailMessage = MailMessage::Load(u"LinksSample.eml");

SharedPtr<HtmlSaveOptions> options = MakeObject<HtmlSaveOptions>();

// download the images the HTML body links to and store them as attachments
options->set_ExtractHTMLBodyResourcesAsAttachments(true);

// the event reports every resource that is written
options->ResourceHtmlRendering.connect(std::function<void(SharedPtr<Object>, SharedPtr<ResourceHtmlRenderingEventArgs>)>(
    [](SharedPtr<Object> sender, SharedPtr<ResourceHtmlRenderingEventArgs> e)
    {
        Console::WriteLine(u"resource: " + e->get_PathToResourceFile());
    }));

mailMessage->Save(u"WithExtractedResources.html", options);