Работа с вложениями и встроенными объектами с использованием библиотеки C++ Email Parser
Управление вложениями электронной почты
Вложение электронной почты — это файл на компьютере, который отправляется вместе с сообщением электронной почты. Файл может быть отправлен как отдельное сообщение, так и в составе сообщения, к которому он прикреплен. Класс Attachment используется вместе с классом MailMessage. Все сообщения имеют тело. В дополнение к телу, вы можете захотеть отправить дополнительные файлы. Эти файлы отправляются как вложения и представлены экземплярами класса Attachment. Вы можете отправить любое количество вложений, но размер вложения ограничен почтовым сервером. Gmail, например, не поддерживает размеры файлов более 10MB.
Попробуйте это!
Добавьте или удалите вложения электронной почты с помощью бесплатного Aspose.Email Editor App.
Добавление вложения
Чтобы прикрепить вложение к сообщению электронной почты, выполните следующие шаги:
- Создайте экземпляр класса MailMessage.
- Создайте экземпляр класса Attachment.
- Загрузите вложение в экземпляр Attachment.
- Добавьте экземпляр Attachment в экземпляр класса MailMessage.
Следующий фрагмент кода показывает, как добавить вложение к сообщению электронной почты.
For complete examples and data files, please go to https://github.com/kashifiqb/Aspose.Email-for-C | |
// The path to the File directory. | |
System::String dataDir = RunExamples::GetDataDir_Email(); | |
// Create an instance of MailMessage class | |
System::SharedPtr<MailMessage> message = System::MakeObject<MailMessage>(); | |
message->set_From(L"sender@sender.com"); | |
message->get_To()->Add(L"receiver@gmail.com"); | |
// Load an attachment | |
System::SharedPtr<Attachment> attachment = System::MakeObject<Attachment>(dataDir + L"1.txt"); | |
// Add Multiple Attachment in instance of MailMessage class and Save message to disk | |
message->get_Attachments()->Add(attachment); | |
message->AddAttachment(System::MakeObject<Attachment>(dataDir + L"1.jpg")); | |
message->AddAttachment(System::MakeObject<Attachment>(dataDir + L"1.doc")); | |
message->AddAttachment(System::MakeObject<Attachment>(dataDir + L"1.rar")); | |
message->AddAttachment(System::MakeObject<Attachment>(dataDir + L"1.pdf")); | |
message->Save(dataDir + L"outputAttachments_out.msg", SaveOptions::get_DefaultMsgUnicode()); |
Выше мы описали, как добавить вложения к сообщению электронной почты с помощью Aspose.Email. Далее показано, как удалить вложения и отобразить информацию о них на экране.
Удаление вложения
Чтобы удалить вложение, выполните следующие шаги:
- Создайте экземпляр класса Attachment.
- Загрузите вложение в экземпляр класса Attachment.
- Добавьте вложение в экземпляр класса MailMessage.
- Удалите вложения из экземпляра класса Attachment, используя экземпляр класса MailMessage.
Следующий фрагмент кода показывает, как удалить вложение.
For complete examples and data files, please go to https://github.com/kashifiqb/Aspose.Email-for-C | |
// The path to the File directory. | |
System::String dataDir = RunExamples::GetDataDir_Email(); | |
System::String dstEmailRemoved = dataDir + L"RemoveAttachments.msg"; | |
// Create an instance of MailMessage class | |
System::SharedPtr<MailMessage> message = System::MakeObject<MailMessage>(); | |
message->set_From(L"sender@sender.com"); | |
message->get_To()->Add(L"receiver@gmail.com"); | |
// Load an attachment | |
System::SharedPtr<Attachment> attachment = System::MakeObject<Attachment>(dataDir + L"1.txt"); | |
// Add Multiple Attachment in instance of MailMessage class and Save message to disk | |
message->get_Attachments()->Add(attachment); | |
message->AddAttachment(System::MakeObject<Attachment>(dataDir + L"1.jpg")); | |
message->AddAttachment(System::MakeObject<Attachment>(dataDir + L"1.doc")); | |
message->AddAttachment(System::MakeObject<Attachment>(dataDir + L"1.rar")); | |
message->AddAttachment(System::MakeObject<Attachment>(dataDir + L"1.pdf")); | |
// Remove attachment from your MailMessage and Save message to disk after removing a single attachment | |
message->get_Attachments()->Remove(attachment); | |
message->Save(dstEmailRemoved, SaveOptions::get_DefaultMsgUnicode()); | |
// Create a loop to display the no. of attachments present in email message | |
{ | |
auto getAttachment_enumerator = (message->get_Attachments())->GetEnumerator(); | |
decltype(getAttachment_enumerator->get_Current()) getAttachment; | |
while (getAttachment_enumerator->MoveNext() && (getAttachment = getAttachment_enumerator->get_Current(), true)) | |
{ | |
// Save your attachments here and Display the the attachment file name | |
getAttachment->Save(dataDir + L"/RemoveAttachments/" + L"attachment_out" + getAttachment->get_Name()); | |
System::Console::WriteLine(getAttachment->get_Name()); | |
} | |
} |
Отображение имени файла вложения
Чтобы отобразить имя файла вложения, выполните следующие шаги:
- Переберите вложения в сообщении электронной почты и
- Сохраните каждое вложение.
- Отобразите имя каждого вложения на экране.
Следующий фрагмент кода показывает, как отобразить имя файла вложения на экране.
For complete examples and data files, please go to https://github.com/kashifiqb/Aspose.Email-for-C | |
// Create a loop to display the no. of attachments present in email message | |
{ | |
auto attachment_enumerator = (message->get_Attachments())->GetEnumerator(); | |
decltype(attachment_enumerator->get_Current()) attachment; | |
while (attachment_enumerator->MoveNext() && (attachment = attachment_enumerator->get_Current(), true)) | |
{ | |
// Display the the attachment file name | |
System::Console::WriteLine(attachment->get_Name()); | |
} | |
} |
Извлечение вложений электронной почты
Эта тема объясняет, как извлечь вложение из файла электронной почты. Вложение электронной почты — это файл на компьютере, который отправляется вместе с сообщением электронной почты. Файл может быть отправлен как отдельное сообщение, так и в составе сообщения, к которому он прикреплен. Все сообщения электронной почты содержат тело. Кроме тела, вы можете захотеть отправить дополнительные файлы. Эти файлы отправляются как вложения и представлены экземплярами класса Attachment. Класс Attachment используется вместе с классом MailMessage для работы с вложениями. Для извлечения вложений из сообщения электронной почты выполните следующие шаги:
- Создайте экземпляр класса MailMessage.
- Загрузите файл электронной почты в экземпляр MailMessage.
- Создайте экземпляр класса Attachment и используйте его в цикле для извлечения всех вложений.
- Сохраните вложение и отобразите его на экране.
- Укажите адрес отправителя и получателя в экземпляре MailMessage.
- Фрагменты кода извлекают вложения из электронной почты.
Извлеченные вложения в электронной почте |
---|
![]() |
Следующий фрагмент кода показывает, как извлечь вложения из электронной почты. |
For complete examples and data files, please go to https://github.com/kashifiqb/Aspose.Email-for-C | |
// The path to the File directory. | |
System::String dataDir = RunExamples::GetDataDir_Email(); | |
// Create an instance of MailMessage and load an email file | |
System::SharedPtr<MailMessage> mailMsg = MailMessage::Load(dataDir + L"Message.msg", System::MakeObject<MsgLoadOptions>()); | |
{ | |
auto attachment_enumerator = (mailMsg->get_Attachments())->GetEnumerator(); | |
decltype(attachment_enumerator->get_Current()) attachment; | |
while (attachment_enumerator->MoveNext() && (attachment = attachment_enumerator->get_Current(), true)) | |
{ | |
// To display the the attachment file name | |
attachment->Save(dataDir + L"MessageEmbedded_out.msg"); | |
System::Console::WriteLine(attachment->get_Name()); | |
} | |
} |
Получение Content-Description из вложения
API Aspose.Email предоставляет возможность читать Content-Description вложения из заголовка вложения. Следующий фрагмент кода показывает, как получить описание содержимого из вложения.
For complete examples and data files, please go to https://github.com/kashifiqb/Aspose.Email-for-C | |
System::SharedPtr<MailMessage> message = MailMessage::Load(dataDir + L"EmailWithAttandEmbedded.eml"); | |
System::String description = message->get_Attachments()->idx_get(0)->get_Headers()->idx_get(L"Content-Description"); | |
System::Console::WriteLine(description); |
Работа с встроенными объектами
Встроенный объект — это объект, который был создан с помощью одного приложения и заключен в документ или файл, созданный другим приложением. Например, таблица Microsoft Excel может быть встроена в отчет Microsoft Word, или видеофайл может быть встроен в презентацию Microsoft PowerPoint. Когда файл встроен, а не вставлен или скопирован в другой документ, он сохраняет свой исходный формат. Встроенный документ может быть открыт в исходном приложении и изменен.
Встраивание объектов в электронную почту
Класс LinkedResources используется вместе с классом MailMessage для встраивания объектов в ваши сообщения электронной почты. Чтобы добавить встроенный объект, выполните следующие шаги:
- Создайте экземпляр класса MailMessage.
- Укажите значения from, to и subject в экземпляре MailMessage.
- Создайте экземпляр класса AlternateView.
- Создайте экземпляр класса LinkedResources.
- Загрузите встроенный объект в экземпляр LinkedResources.
- Добавьте загруженный встроенный объект в экземпляр класса MailMessage.
- Добавьте экземпляр AlternateViews в экземпляр класса MailMessage.
Фрагменты кода ниже создают сообщение электронной почты с текстовыми и HTML-телами и изображением, встроенным в HTML.
Изображение, встроенное в электронную почту |
---|
Вы можете отправить любое количество встроенных объектов. Размер вложения ограничен почтовым сервером. Gmail, например, не поддерживает размеры файлов более 10MB. Фрагменты кода ниже показывают, как встраивать объекты в электронную почту. |
For complete examples and data files, please go to https://github.com/kashifiqb/Aspose.Email-for-C | |
// The path to the File directory. | |
System::String dataDir = RunExamples::GetDataDir_Email(); | |
System::String dstEmail = dataDir + L"EmbeddedImage.msg"; | |
// Create an instance of the MailMessage class and Set the addresses and Set the content | |
System::SharedPtr<MailMessage> mail = System::MakeObject<MailMessage>(); | |
mail->set_From(System::MakeObject<MailAddress>(L"test001@gmail.com")); | |
mail->get_To()->Add(L"test001@gmail.com"); | |
mail->set_Subject(L"This is an email"); | |
// Create the plain text part It is viewable by those clients that don't support HTML | |
System::SharedPtr<AlternateView> plainView = AlternateView::CreateAlternateViewFromString(L"This is my plain text content", nullptr, L"text/plain"); | |
/* Create the HTML part.To embed images, we need to use the prefix 'cid' in the img src value. | |
The cid value will map to the Content-Id of a Linked resource. Thus <img src='cid:barcode'> will map to a LinkedResource with a ContentId of //'barcode'. */ | |
System::SharedPtr<AlternateView> htmlView = AlternateView::CreateAlternateViewFromString(L"Here is an embedded image.<img src=cid:barcode>", nullptr, L"text/html"); | |
// Create the LinkedResource (embedded image) and Add the LinkedResource to the appropriate view | |
System::SharedPtr<LinkedResource> barcode = System::MakeObject<LinkedResource>(dataDir + L"1.jpg", MediaTypeNames::Image::Jpeg); | |
barcode->set_ContentId(L"barcode"); | |
mail->get_LinkedResources()->Add(barcode); | |
mail->get_AlternateViews()->Add(plainView); | |
mail->get_AlternateViews()->Add(htmlView); | |
mail->Save(dataDir + L"EmbeddedImage_out.msg", SaveOptions::get_DefaultMsgUnicode()); |
Извлечение встроенных объектов
Эта тема объясняет, как извлечь встроенные объекты из файла электронной почты. Встроенный объект — это объект, который был создан с помощью одного приложения и заключен в документ или файл, созданный другим приложением. Например, таблица Microsoft Excel может быть встроена в отчет Microsoft Word, или видеофайл может быть встроен в презентацию Microsoft PowerPoint. Когда файл встроен, а не вставлен или скопирован в другой документ, он сохраняет свой исходный формат. Встроенный документ может быть открыт в исходном приложении и изменен. Чтобы извлечь встроенный объект из сообщения электронной почты, выполните следующие шаги:
- Создайте экземпляр класса MailMessage.
- Загрузите файл электронной почты в экземпляр MailMessage.
- Создайте цикл и создайте в нем экземпляр класса Attachment.
- Сохраните вложение и отобразите его на экране.
- Укажите адрес отправителя и получателя в экземпляре MailMessage.
- Фрагмент кода ниже извлекает встроенные объекты из электронной почты.
Извлеченные встроенные объекты в электронной почте |
---|
![]() |
Следующий фрагмент кода показывает, как извлечь встроенные объекты. |
For complete examples and data files, please go to https://github.com/kashifiqb/Aspose.Email-for-C | |
// The path to the File directory. | |
System::String dataDir = RunExamples::GetDataDir_Email(); | |
// Create an instance of MailMessage and load an email file | |
System::SharedPtr<MailMessage> mailMsg = MailMessage::Load(dataDir + L"Message.msg", System::MakeObject<MsgLoadOptions>()); | |
{ | |
auto attachment_enumerator = (mailMsg->get_Attachments())->GetEnumerator(); | |
decltype(attachment_enumerator->get_Current()) attachment; | |
while (attachment_enumerator->MoveNext() && (attachment = attachment_enumerator->get_Current(), true)) | |
{ | |
// To display the the attachment file name | |
attachment->Save(dataDir + L"MessageEmbedded_out.msg"); | |
System::Console::WriteLine(attachment->get_Name()); | |
} | |
} |