Create and Customize Email Messages Using Aspose.Email for C++

Aspose.Email for C++ provides the MailMessage class to create, customize, and save email messages in different formats. This class allows you to define essential properties such as sender, recipients, subject, and body, and supports saving messages in EML, MSG, and MHTML formats.

The samples in this article use these headers and namespaces:

#include <MailMessage.h>
#include <MailAddress.h>
#include <MailAddressCollection.h>
#include <AlternateView.h>
#include <AlternateViewCollection.h>
#include <LinkedResourceCollection.h>
#include <HtmlLoadOptions.h>
#include <SaveOptions.h>
#include <EmlSaveOptions.h>
#include <MsgSaveOptions.h>
#include <MhtSaveOptions.h>
#include <MailPriority.h>
#include <MailSensitivity.h>
#include <DeliveryNotificationOptions.h>
#include <Mime/HeaderCollection.h>
#include <system/text/encoding.h>
#include <system/convert.h>

using namespace System;
using namespace Aspose::Email;

Create a New Email Message

The following code sample demonstrates how to create and configure a new email message using Aspose.Email for C++.

  1. Create an instance of the MailMessage class.
  2. Set message properties such as From, To, Cc, Subject, and HtmlBody.
  3. Optionally, save the message in multiple formats (EML, MSG, MHTML, etc.).

The format of the saved file is chosen by the SaveOptions passed to Save; the static get_Default... methods return ready-made options for each format.

SharedPtr<MailMessage> message = MakeObject<MailMessage>();

message->set_Subject(u"New message created by Aspose.Email for C++");
message->set_HtmlBody(u"<b>This line is in bold.</b> <br/> <br/><font color=blue>This line is in blue color</font>");
message->set_From(MakeObject<MailAddress>(u"from@domain.com", u"Sender Name", false));

message->get_To()->Add(MakeObject<MailAddress>(u"to1@domain.com", u"Recipient 1", false));
message->get_To()->Add(MakeObject<MailAddress>(u"to2@domain.com", u"Recipient 2", false));
message->get_CC()->Add(MakeObject<MailAddress>(u"cc1@domain.com", u"Recipient 3", false));
message->get_CC()->Add(MakeObject<MailAddress>(u"cc2@domain.com", u"Recipient 4", false));

// one message, four file formats
message->Save(u"NewMessage.eml", SaveOptions::get_DefaultEml());
message->Save(u"NewMessage.emlx", SaveOptions::get_DefaultEmlx());
message->Save(u"NewMessage.msg", SaveOptions::get_DefaultMsgUnicode());
message->Save(u"NewMessage.mhtml", SaveOptions::get_DefaultMhtml());

Using Friendly Names for Email Addresses

A friendly name makes an email address more readable. For example, John Smith <jsmith@domain.com> instead of just jsmith@domain.com.

A MailAddress takes the friendly name as the second argument of its constructor. In C++, pass that name as a String, as in the sample: MailAddress also has a constructor that takes a bool as its second argument, and a bare string literal converts to bool more readily than to String, so MailAddress(u"kyle@to.com", u"Kyle Huang") would create an address without a name. The sample below adds To, Cc and Bcc recipients with both an address and a friendly name to an existing message.

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

message->get_To()->Add(MakeObject<MailAddress>(u"kyle@to.com", String(u"Kyle Huang")));
message->get_CC()->Add(MakeObject<MailAddress>(u"guangzhou@cc.com", String(u"Guangzhou Team")));
message->get_Bcc()->Add(MakeObject<MailAddress>(u"ahaq@bcc.com", String(u"Ammad ulHaq")));

message->Save(u"MessageWithFriendlyNames.eml", SaveOptions::get_DefaultEml());

SharedPtr<MailMessage> saved = MailMessage::Load(u"MessageWithFriendlyNames.eml");
for (SharedPtr<MailAddress> address : saved->get_To())
{
    Console::WriteLine(u"To: " + address->get_DisplayName() + u" <" + address->get_Address() + u">");
}

Set Mail Body Content

The MailMessage class allows you to define the email body in HTML format. You can also provide alternate views for different email clients using the AlternateView class.

Setting HTML Body

Assigning a string to set_HtmlBody makes the message an HTML message: mail clients render the markup instead of showing it as text, and IsBodyHtml reports true.

SharedPtr<MailMessage> message = MakeObject<MailMessage>();
message->set_HtmlBody(u"<html><body>This is the <b>HTML</b> body</body></html>");

Console::WriteLine(u"Is the body HTML? " + Convert::ToString(message->get_IsBodyHtml()));

Setting Alternate Text

Some email clients cannot display HTML content. To ensure your message is readable for all recipients, you can add an alternate plain text version using the AlternateView class. It allows you to include multiple versions of an email message in different formats. For example, if your main message body is HTML, you can also attach a plain text version as an alternative.

AlternateView::CreateAlternateViewFromString builds such a view from a string, and the AlternateViews collection of the message takes it.

SharedPtr<MailMessage> message = MakeObject<MailMessage>();
message->set_HtmlBody(u"<p>The <b>formatted</b> version of the message.</p>");

SharedPtr<AlternateView> alternate = AlternateView::CreateAlternateViewFromString(u"The plain text version of the message.");
message->get_AlternateViews()->Add(alternate);

Console::WriteLine(u"Alternate views: " + Convert::ToString(message->get_AlternateViews()->get_Count()));

The AlternateView class also manages resources used within the email body:

  • LinkedResources – a collection of embedded items (such as images or attachments) that are referenced by links in the message content.
  • set_BaseUri() – defines the base URL used to resolve relative links or resource paths in the message body.

Set the Default Text Encoding

PreferredTextEncoding sets one encoding for everything a reader sees: the display names of the sender and the recipients, the subject and the body. Assign it before the text is written, otherwise the parts that were set earlier keep the encoding they were given.

SharedPtr<MailMessage> msg = MakeObject<MailMessage>();

// The encoding applied to the display names, the subject and the body
msg->set_PreferredTextEncoding(System::Text::Encoding::GetEncoding(28591));

msg->set_From(MakeObject<MailAddress>(u"dmo@domain.com", String(u"démo")));
msg->get_To()->Add(MakeObject<MailAddress>(u"dmo@domain.com", String(u"démo")));
msg->set_Subject(u"démo");
msg->set_HtmlBody(u"démo");

msg->Save(u"PreferredEncoding.msg", SaveOptions::get_DefaultMsg());

Individual parts can also be encoded separately: SubjectEncoding applies to the subject only and BodyEncoding to the body only.

Set a Plain Text Body

Body holds the text/plain part of the message, HtmlBody the text/html one. Setting both produces a message with two alternatives, which is what most mail clients expect.

// plain text body
SharedPtr<MailMessage> plain = MakeObject<MailMessage>();
plain->set_Body(u"This is a plain text body");

// HTML body
SharedPtr<MailMessage> html = MakeObject<MailMessage>();
html->set_HtmlBody(u"<html><body>This is the HTML body</body></html>");

// the encoding used for the body text
html->set_BodyEncoding(System::Text::Encoding::get_UTF8());

Console::WriteLine(u"Plain: " + plain->get_Body());
Console::WriteLine(u"Html: " + html->get_HtmlBody());

IsBodyHtml tells the two kinds of message apart: it is false for a message that has a plain text body only, and true as soon as an HTML body is present - also when a plain text alternative is set next to it.

SharedPtr<MailMessage> plain = MakeObject<MailMessage>();
plain->set_Body(u"This is a plain text body");

SharedPtr<MailMessage> html = MakeObject<MailMessage>();
html->set_HtmlBody(u"<html><body>This is the HTML body</body></html>");

SharedPtr<MailMessage> both = MakeObject<MailMessage>();
both->set_Body(u"Plain alternative");
both->set_HtmlBody(u"<html><body>HTML alternative</body></html>");

// IsBodyHtml tells whether the message carries an HTML body
Console::WriteLine(u"Plain message, IsBodyHtml: " + Convert::ToString(plain->get_IsBodyHtml()));
Console::WriteLine(u"HTML message, IsBodyHtml: " + Convert::ToString(html->get_IsBodyHtml()));
Console::WriteLine(u"Both bodies, IsBodyHtml: " + Convert::ToString(both->get_IsBodyHtml()));

Build a Message from an HTML File

A ready-made HTML page can become the body of a message. Load the file with HtmlLoadOptions and point PathToResources at the folder that holds the images the page refers to: they are read from disk and embedded into the message as inline resources, so the result stays self-contained after the source files are gone. ShouldAddPlainTextView additionally produces a plain text alternative from the markup.

SharedPtr<HtmlLoadOptions> htmlLoadOptions = MakeObject<HtmlLoadOptions>();
htmlLoadOptions->set_PathToResources(u".");      // folder that holds the referenced images
htmlLoadOptions->set_ShouldAddPlainTextView(true); // add a text/plain alternative

SharedPtr<MailMessage> message = MailMessage::Load(u"body_content.html", htmlLoadOptions);

message->set_From(MakeObject<MailAddress>(u"sender@domain.com"));
message->get_To()->Add(u"receiver@domain.com");
message->set_Subject(u"New message from HTML");

message->Save(u"FromHtml.eml", SaveOptions::get_DefaultEml());

// the images are now embedded in the message, not referenced from disk
Console::WriteLine(u"Linked resources: " + Convert::ToString(message->get_LinkedResources()->get_Count()));
Console::WriteLine(u"Alternate views: " + Convert::ToString(message->get_AlternateViews()->get_Count()));

Specify Multiple Recipients

To, CC and Bcc are MailAddressCollection objects. Addresses in CC are visible to everyone; those in Bcc are not shown to the other recipients. The Add overload that takes a string parses a comma-separated list, so several addresses can be added at once.

SharedPtr<MailMessage> eml = MakeObject<MailMessage>();
eml->set_From(u"sender@sender.com");

// primary recipients
eml->get_To()->Add(u"receiver1@receiver.com");
eml->get_To()->Add(u"receiver2@receiver.com");

// carbon copies - visible to everyone
eml->get_CC()->Add(u"cc1@receiver.com");

// blind carbon copies - hidden from the other recipients
eml->get_Bcc()->Add(u"bcc1@receiver.com");

// a comma-separated list is parsed into separate addresses
eml->get_To()->Add(u"receiver3@receiver.com, receiver4@receiver.com");

Console::WriteLine(u"To: " + Convert::ToString(eml->get_To()->get_Count()) +
    u", CC: " + Convert::ToString(eml->get_CC()->get_Count()) +
    u", Bcc: " + Convert::ToString(eml->get_Bcc()->get_Count()));

Set Additional Properties

Besides the addresses and the body, MailMessage exposes the other fields of the message header:

Property Header
Date Date - the composition time. The delivery time is added by the SMTP server in its own Received headers.
Priority Importance of the message: MailPriority Low, Normal or High.
Sensitivity Handling hint: MailSensitivity Normal, Personal, Private, CompanyConfidential.
XMailer X-Mailer - the program that produced the message.
MessageId Message-ID.
ReplyToList Reply-To - where the answers should go.
SharedPtr<MailMessage> eml = MakeObject<MailMessage>(u"sender@domain.com", u"receiver@domain.com",
    u"Some subject", u"Some body text");

eml->set_Date(DateTime::get_Now());                          // the Date header
eml->set_Priority(MailPriority::High);                       // X-Priority / Importance
eml->set_Sensitivity(MailSensitivity::Normal);               // Sensitivity
eml->set_XMailer(u"Aspose.Email for C++");                   // X-Mailer
eml->set_MessageId(u"<unique-id@domain.com>");               // Message-ID
eml->get_ReplyToList()->Add(u"reply@domain.com");            // Reply-To

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

Request a Read Receipt

Two different notifications can be requested. DeliveryNotificationOptions asks the servers on the way for a delivery status notification, while ReadReceiptTo asks the recipient’s mail client to confirm that the message was opened.

SharedPtr<MailMessage> eml = MakeObject<MailMessage>();
eml->set_From(u"sender@sender.com");
eml->set_To(u"receiver@receiver.com");
eml->set_HtmlBody(u"<html><body>This is the HTML body</body></html>");

// ask the receiving server for a delivery status notification
eml->set_DeliveryNotificationOptions(DeliveryNotificationOptions::OnSuccess);

// ask the mail client for a read receipt
eml->set_ReadReceiptTo(u"sender@sender.com");

// some clients look at these headers instead
eml->get_Headers()->Add(u"Return-Receipt-To", u"sender@sender.com");

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

A read receipt is a request, not a guarantee: the client may not support it, the feature may be switched off, or the reader may simply decline. Handling the notification that comes back is described in Email Messages Advanced Management.

Customize the Email Headers

The header fields that have no dedicated property are reached through Headers, a HeaderCollection:

  • Add appends a header at the end of the collection;
  • Insert places it before the existing headers with the same name, which is what trace headers such as Received need;
  • Set replaces every existing value of a header;
  • Get and GetDecodedValue read a value back.
SharedPtr<MailMessage> eml = MakeObject<MailMessage>();
eml->set_ReplyToList(u"reply@reply.com");
eml->set_From(u"sender@sender.com");
eml->set_To(u"receiver1@receiver.com");
eml->get_CC()->Add(u"receiver2@receiver.com");
eml->get_Bcc()->Add(u"receiver3@receiver.com");
eml->set_Subject(u"test mail");
eml->set_Date(DateTime(2006, 3, 6));
eml->set_XMailer(u"Aspose.Email");

// a custom header, appended at the end of the collection
eml->get_Headers()->Add(u"secret-header", u"mystery");

// Insert places the header before the other headers with the same name
eml->get_Headers()->Insert(u"Received", u"from mail.domain.com");

// read a header back, decoded if it was encoded
Console::WriteLine(eml->get_Headers()->Get(u"secret-header"));
Console::WriteLine(eml->GetHeadersAsString());

GetHeadersAsString returns the whole header block as it will be written to the file, which is handy while debugging.