العمل مع المرفقات والكائنات المدمجة

العمل مع المرفقات

مرفقات البريد الإلكتروني هي ملفات تُرسل مع رسالة البريد. يمكن أن تشمل هذه الملفات مستندات، صور، أرشيفات، وأكثر.

في Aspose.Email للغة C++، تُدار المرفقات عبر الـ Attachment فئة، التي تعمل مع الـ MailMessage فئة. يمكنك إضافة، إزالة، استخراج أو عرض المرفقات برمجياً.

ملاحظة: الحد الأقصى لحجم المرفق يعتمد على خادم البريد (على سبيل المثال، يحد Gmail حجم المرفقات إلى 10 ميجابايت).

العينات في هذه المقالة تستخدم هذه الرؤوس والمساحات الاسمية:

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

إضافة مرفقات إلى بريد إلكتروني

لإرفاق ملف واحد أو أكثر إلى رسالة بريد إلكتروني، اتبع الخطوات التالية:

  1. إنشاء مثيل من الـ MailMessage فئة.
  2. Create Attachment كائنات لكل ملف.
  3. أضف المرفقات إلى الرسالة - عبر المرفقات مجموعة أو باستخدام AddAttachment.
  4. احفظ الرسالة إذا لزم الأمر.
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()));

إزالة المرفقات من بريد إلكتروني

يمكنك بسهولة إزالة المرفقات من رسالة باستخدام الـ Remove() طريقة الـ المرفقات مجموعة.

يوضح المقتطف التالي كيفية إزالة مرفق:

  1. تحميل أو إنشاء MailMessage كائن.
  2. اعثر على المرفق لإزالته - احتفظ بالكائن الذي أضفته، أو ابحث عنه في المجموعة.
  3. مرّر إلى Remove(); RemoveAt() يزيل المرفق عند موضع معين بدلاً من ذلك.
  4. اختياريًا، اعرض المرفقات المتبقية.
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());
}

عرض أسماء ملفات المرفقات

الـ Name من المرفق هو اسم الملف الذي تعطيه الرسالة له. حلقة عبر المجموعة تُدرجهم جميعًا:

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

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

استخراج المرفقات من بريد إلكتروني

لاستخراج وحفظ المرفقات من ملف بريد إلكتروني موجود، اتبع الخطوات التالية:

  1. حمّل الرسالة باستخدام الـ MailMessage فئة.
  2. التكرار عبر الـ المرفقات مجموعة.
  3. احفظ كل مرفق على القرص باستخدام Attachment::Save واختياريًا تعرض اسمه.

القطعة البرمجية التالية تحفظ كل مرفق لرسالة في مجلد، كلٌ باسمه الخاص:

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

|المرفقات المستخرجة في البريد الإلكتروني| | :- | |todo:image_alt_text|

قراءة وصف محتوى المرفق

يحمل المرفق رؤوس MIME خاصة به. يحمل الرأس الاختياري Content-Description وصفًا قصيرًا للملف؛ يُقرأ من Headers مجموعة المرفق. العينة تكتب الرأس وتقرأه مرة أخرى من الرسالة المحفوظة.

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

العمل مع الكائنات المضمَّنة

كائن مدمج هو ملف تم إنشاؤه في تطبيق واحد ومضمّن داخل مستند أو بريد إلكتروني آخر. على سبيل المثال، يمكن دمج جدول بيانات Microsoft Excel داخل مستند Word، أو يمكن دمج صورة مباشرة في جسم البريد الإلكتروني.

عند دمج كائن (ليس مجرد إرفاق أو ربط)، يحتفظ بتنسيقه الأصلي ويمكن فتحه أو تحريره في التطبيق الأصلي.

تضمين الكائنات في بريد إلكتروني

لدمج صورة أو كائن آخر في رسالة بريد إلكتروني، استخدم الـ LinkedResource فئة مع الـ MailMessage و AlternateView فئات. يتيح لك ذلك تضمين صور أو وسائط مدمجة تظهر مباشرة في جسم الرسالة.

يوضح مثال الشيفرة التالي كيفية إنشاء رسالة بريد إلكتروني تحتوي على نص عادي ومحتوى HTML يتضمن صورة مدمجة:

  1. إنشاء مثيل من الـ MailMessage فئة.
  2. حدد حقول المرسل، المستقبل، والموضوع.
  3. إنشاء جسم نص عادي باستخدام AlternateView.
  4. إنشاء جسم HTML يحتوي على مرجع إلى الكائن المدمج باستخدام الـ cid (Content-ID). اكتب المرجع بين علامات اقتباس مزدوجة، src="cid:barcode": بهذا الشكل يُعرّف برنامج يحمل الرسالة لاحقًا الصورة كموارد مضمنة بدلاً من مرفق.
  5. إنشاء مثيل من الـ LinkedResource فئة وحمّل الكائن.
  6. عيّن معرّف Content-ID للمورد المرتبط.
  7. أضف المورد المرتبط والواجهات البديلة إلى الرسالة.
  8. احفظ أو أرسل رسالة البريد الإلكتروني.
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());

ملاحظة: > يمكنك دمج عدة كائنات، لكن الحد الأقصى لحجم الرسالة يحدّه خادم البريد الخاص بك. على سبيل المثال، يحد Gmail حجم الرسالة إلى 10 ميجابايت.

استخراج الكائنات المدمجة من بريد إلكتروني

يمكنك أيضًا استخراج الكائنات المدمجة، مثل الصور، من رسالة بريد إلكتروني موجودة. هي ليست مرفقات: تُدرج الرسالة المحملة إياها في LinkedResources مجموعة. العملية مشابهة لاستخلاص المرفقات:

  1. حمِّل ملف البريد الإلكتروني إلى MailMessage.
  2. تجول في الموارد المرتبطة.
  3. احفظ كل كائن مدمج على القرص؛ معرف المحتوى يوضح أي مرجع في جسم HTML ينتمي إليه.
  4. اختياريًا، عرض أسماء الملفات في وحدة التحكم.
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);
}

|الكائنات المدمجة المستخرجة في البريد| | :- | |todo:image_alt_text|

طرق أخرى للعمل مع المرفقات

إضافة مرفق مرجعي

المرفق المرجعي لا يسافر مع الرسالة: يحمل رابطًا لملف في موقع مشترك، لذا يفتح المتلقون دائمًا النسخة الحالية وتبقى الرسالة صغيرة. ReferenceAttachment يأخذ URI، بينما ProviderType يسمي خدمة التخزين و PermissionType ما يحصل عليه المتلقون من وصول.

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

تحديد الرسائل المدمجة والمحتوى الموقّع

IsEmbeddedMessage يخبر ما إذا كان المرفق نفسه رسالة؛ يمكن تحليل مثل هذا المرفق باستخدام MailMessage::Load مباشرة من تدفق محتواها. الرسالة الموقعة حالة مختلفة: تتكون من واحد smime.p7m جزء، و IsSigned معًا مع IsEncrypted تُبلغ عن ذلك.

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

الصور المضمنة

الصورة المدمجة لا تُدرج كمرفق؛ إنها LinkedResource whose ContentId يشير إليها جسم HTML عبر cid: URL.

إضافة صورة مدمجة إلى النص

تُوضع صورة في النص بإضافتها إلى LinkedResources مع معرف محتوى (Content-ID) والإشارة إلى ذلك المعرف من HTML - العينة الكاملة في دمج الكائنات في بريد إلكتروني. عدد الكائنات المدمجة يقتصر فقط على حجم الرسالة الذي يقبله خادم البريد.

إزالة صورة مضمنة من النص

RemoveAt و مسح كلاهما يأخذ علمًا يحذف أيضًا الـ <img src=cid:...> من المرجع في HTML، لذا لا يبقى أي صورة مكسورة. تذكر أن العروض البديلة تحتفظ بنسخها الخاصة من الموارد.

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

استخلاص الصور المرتبطة من جسم HTML

بعض النشرات الإخبارية لا تدمج صورها مطلقًا - يشير جسم HTML إليها بروابط عادية http الروابط، وتصبح الرسالة مكسورة بمجرد توقف هذه الروابط عن العمل. ضبط ExtractHTMLBodyResourcesAsAttachments يجعل المكتبة تجلب هذه الموارد أثناء تصدير الرسالة وتدمجها في المخرجات. الـ ResourceHtmlRendering التقارير الحدثية تعرض كل مورد تمت معالجته.

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