Creating and Setting Contents of Emails in .NET

Create New Email Message

The MailMessage class represents an email message and allows developers to create a new email message. Basic email properties like From, To, Subject and body can be easily attached to the newly created mail message. Similarly, we can save the mail message into different formats like EML, MSG, and MHTML.

Steps: Create New Email:

Code Steps:

  1. Create an instance of the MailMessage class.
  2. Set mail message properties.
  3. Save the mail message in different formats e.g.
    1. EML using SaveOptions.DefaultEml
    2. EmlxFormat (Apple Email) using CreateSaveOptions method.
    3. MSG Unicode using SaveOptions.DefaultMsgUnicode
    4. MHTML using SaveOptions.DefaultMhtml

The following code snippet shows you how to create a new email with different properties.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
// Create a new instance of MailMessage class
MailMessage message = new MailMessage();
// Set subject of the message, Html body and sender information
message.Subject = "New message created by Aspose.Email for .NET";
message.HtmlBody = "<b>This line is in bold.</b> <br/> <br/>" + "<font color=blue>This line is in blue color</font>";
message.From = new MailAddress("from@domain.com", "Sender Name", false);
// Add TO recipients and Add CC recipients
message.To.Add(new MailAddress("to1@domain.com", "Recipient 1", false));
message.To.Add(new MailAddress("to2@domain.com", "Recipient 2", false));
message.CC.Add(new MailAddress("cc1@domain.com", "Recipient 3", false));
message.CC.Add(new MailAddress("cc2@domain.com", "Recipient 4", false));
// Save message in EML, EMLX, MSG and MHTML formats
message.Save(dataDir + "CreateNewMailMessage_out.eml", SaveOptions.DefaultEml);
message.Save(dataDir + "CreateNewMailMessage_out.emlx", SaveOptions.CreateSaveOptions(MailMessageSaveType.EmlxFormat));
message.Save(dataDir + "CreateNewMailMessage_out.msg", SaveOptions.DefaultMsgUnicode);
message.Save(dataDir + "CreateNewMailMessage_out.mhtml", SaveOptions.DefaultMhtml);

Specifying Multiple Recipients

The MailMessage represents an email message. Instances of the MailMessage class are used to construct email messages that are transmitted to an SMTP server using the SmtpClient class. This topic demonstrates how to specify more than one email address. Email addresses can be specified using the MailMessage class. The email addresses used in the MailMessage class are:

  • To - Recipient addresses can be specified in the ‘To’ field. The ‘To’ field recipients are the primary message audience. There can be more than one recipient address
  • Cc - Cc stands for “carbon copy”, or “courtesy copy”, and lets you add email recipients who need to see the email but who are not necessarily expected to act on it. Managers, for example, or members of your team who need to be aware of a conversation. With Aspose.Email, Cc addresses can be specified in your code. This way, automated emails, or all emails to a specific address, can be copied to relevant personnel.
  • Bcc -  Where a Cc appears in the email information that the main recipients see, a Bcc doesn’t. It is meant for hidden notification.

To specify multiple email addresses in an email message, follow these steps:

Steps: Specify Multiple Recipients of Email using C# | Steps: Send Email to Multiple Recipients in C#

  1. Create an instance of the MailMessage class.
  2. Specify the From and multiple To, Cc and Bcc addresses using the MailMessage instance.
  3. Create an instance of the SmtpClient class and send the email using the Send method.

The code sample below shows how multiple To, Cc, and Bcc addresses can be specified.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Declare message as MailMessage instance
// Create an Instance of MailMessage class
MailMessage message = new MailMessage();
// Specify From address
message.From = "sender@sender.com";
// Specify recipients’ mail addresses
message.To.Add("receiver1@receiver.com");
message.To.Add("receiver2@receiver.com");
message.To.Add("receiver3@receiver.com");
// Specify CC addresses
message.CC.Add("CC1@receiver.com");
message.CC.Add("CC2@receiver.com");
// Specify BCC addresses
message.Bcc.Add("Bcc1@receiver.com");
message.Bcc.Add("Bcc2@receiver.com");
// Create an instance of SmtpClient Class
SmtpClient client = new SmtpClient();
// Specify your mailing host server, Username, Password, Port
client.Host = "smtp.server.com";
client.Username = "Username";
client.Password = "Password";
client.Port = 25;
try
{
// Client.Send will send this message
client.Send(message);
// Display ‘Message Sent’, only if message sent successfully
Console.WriteLine("Message sent");
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(ex.ToString());
}

Changing email addresses to a friendly name

The programming samples below demonstrate how to change email addresses to friendly names in an email message. A friendly name is a name that is more human-friendly than the email address, for example John Smith instead of js346@domain.com. When sending an email, we can associate a friendly name with an email address in the MailMessage class constructor.

To change email addresses to friendly names in an email message, follow these steps:

Steps: Change Email Addresses to Friendly Names in C# | Steps: Send Email after Changing Email Addresses to Friendly Names in C#

  1. Create an instance of the MailMessage class and specify email addresses in the To and From fields along with friendly names.
  2. Specify the Cc and Bcc email addresses along with friendly names by calling the MailMessage class constructor in the MailMessage instance.
  3. Create an instance of the SmtpClient class and send the email using the Send method.

The following code snippet shows you how to display Names for email addresses.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
string dataDir = RunExamples.GetDataDir_Email();
MailMessage message = MailMessage.Load(dataDir + "test.eml");
// A To address with a friendly name can also be specified like this
message.To.Add(new MailAddress("kyle@to.com", "Kyle Huang"));
// Specify Cc and Bcc email address along with a friendly name
message.CC.Add(new MailAddress("guangzhou@cc.com", "Guangzhou Team"));
message.Bcc.Add(new MailAddress("ahaq@bcc.com", "Ammad ulHaq "));
message.Save(dataDir + "MessageWithFrienlyName_out.eml", SaveOptions.DefaultEml);

Set Mail Body

The MailMessage class represents an email message. Instances of the MailMessage class are used to construct email messages that are transmitted to an SMTP server for delivery using the SmtpClient class. A mail body can be specified using the Body and HtmlBody properties of the MailMessage class. The MailMessage class also allows you to add alternate views to the email.

This article shows how to add body and alternate views to the email.

Setting HTML Body

HtmlBody is used to specify the HTML content of a message body. HtmlBody must be enclosed between tags. The following code snippet shows you how to set HTML body.

Steps: Set Email HTML Body in C#

  1. Create an instance of MailMessage class.
  2. Set email HTML body using MailMessage.HtmlBody property.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Declare message as MailMessage instance
MailMessage message = new MailMessage();
// Specify HtmlBody
message.HtmlBody = "<html><body>This is the HTML body</body></html>";

Setting Alternate Text

Use the AlternateView class to specify copies of an email message in different formats. For example, if you send a message in HTML, you might also want to provide a plain text version in case some of the recipients use email readers that cannot display HTML content. This class has two properties, LinkedResources and BaseUri, which are used to resolve URLs within the content of the email.

  • LinkedResources is a collection of LinkedResource objects. When rendered, URLs within the email’s content are first matched against the URLs in the Content Link of each LinkedResource object in the LinkedResources collection and resolved.
  • BaseUri is used by the mail reader to resolve relative URLs within the body, and also to resolve relative Content Link URLs, in the LinkedResources collection.

The following code snippet shows you how to set alternate text.

Steps: Set Email Alternate Text in C#

  1. Create an instance of MailMessage class.
  2. Create AlternateView to view an email message using the content specified in the string.
  3. Add alternate text using Add method of MailMessage.AlternateViews collection.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
AlternateView alternate;
// Creates AlternateView to view an email message using the content specified in the //string
alternate = AlternateView.CreateAlternateViewFromString("Alternate Text");
// Adding alternate text
message.AlternateViews.Add(alternate);

Specifying Mail Body Encoding

The content type defines the email content format: the character set, for example. The encoding formats provided in System.Text.Encoding are:

  • ASCII: Encoding for the ASCII (7 bit) character set.
  • Default: Encoding for the system’s current ANSI code page.
  • Unicode: Encoding for the Unicode format in little-endian byte order.
  • BigEndianUnicode: Encoding for the Unicode format in the big-endian byte order.
  • UTF7: Encoding for the UTF-7 format.
  • UTF8: Encoding for the UTF-8 format.

Aspose.Email uses the BodyEncoding property of the MailMessage class to specify the email body encoding. To encode the body of an email message, follow the steps given below:

Steps: Specifying Mail Body Encoding

Code Steps:

  1. Create an instance of the MailMessage class.
  2. Specify the sender, receiver and HTML body email in the MailMessage instance.
  3. Specify the BodyEncoding property value.
  4. Create an instance of the SmtpClient class and send the email using the Send method.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create an Instance of MailMessage class
MailMessage message = new MailMessage();
// Specify From, To, HtmlBody, BodyEncoding field
message.From = "sender@sender.com";
message.To.Add("receiver@receiver.com");
message.HtmlBody = "<html><body>This is the Html body</body></html>";
message.BodyEncoding = Encoding.ASCII;
// Create an instance of SmtpClient Class and Specify your mailing host server, Username, Password and Port
SmtpClient client = new SmtpClient();
client.Host = "smtp.server.com";
client.Username = "Username";
client.Password = "Password";
client.Port = 25;
// Client.Send will send this message
client.Send(message);

MailMessage Features

The MailMessage class represents the content of an email message. Instances of the MailMessage class are used to construct an email message that is transmitted to an SMTP server for delivery using the SmtpClient class. This article shows how to use MailMessage class utility features for controlling the following email features:

  • Date and time - Through the MailMessage class Date property we get or set an email’s date and time.
  • Message priority - The MailPriority class specifies priority levels for sending an email message. It can be low, normal or high. Priority influences transmission speed and delivery.
  • Message sensitivity - The MailSensitivity class specifies five levels of sensitivity.
  • Delivery notification - Delivery notifications let senders know that the email they sent has been delivered to the recipient’s inbox.

By default, the date is the actual date that the message was sent, and time is the time it was sent, as displayed by Microsoft Outlook. However, the real email delivery time is added by the SMTP server itself in the mail header. For example, below is a common mail header, where Date sets the field Date.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Add by SMTP server in delivery emails
Received: from ip-123.56.99.216.dsl-cust.ca.inter.net ([216.99.56.123]) by Aspose.secureserver.net with MailEnable ESMTP; Thu, 22 Feb 2007 13:58:57 -0700
// Add by SMTP server in delivery emails
Return-Path: <xyz@oikoscucine.it>
// Add by SMTP server in delivery emails
Received: from 195.120.225.20 (HELO mail.oikoscucine.it)
by aspose.com with esmtp (:1CYY+<LA*- *1WK@)
id Q8,/O/-.N83@7-9M
for abc@aspose.com; Thu, 22 Feb 2007 20:58:51 +0300
From: "XYZ" <xyz@oikoscucine.it>
To: <abc@aspose.com>
Subject: For ABC
// Date will set the Date field, outlook will show this as
Date: Thu, 22 Feb 2007 20:58:51 +0300
Message-ID: <01c756c4$41b554d0$6c822ecf@dishonestyinsufferably>
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="----=_NextPart_000_0006_01C7569A.58DF4CD0"
X-Mailer: Microsoft Office Outlook, Build 11.0.5510
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1106
Thread-Index: Aca6Q:=ES0M(9-=(<.<1.<Q9@QE6CD==
X-Read: 1

The code snippet below illustrates how each of the features discussed above can be used.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create a new message
MailMessage message = new MailMessage();
message.From = "sender@gmail.com";
message.To = "receiver@gmail.com";
message.Subject = "Using MailMessage Features";
// Specify message date
message.Date = DateTime.Now;
// Specify message priority
message.Priority = MailPriority.High;
// Specify message sensitivity
message.Sensitivity = MailSensitivity.Normal;
// Specify options for delivery notifications
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;

Requesting a Read Receipt

The programming samples below show how you can request a read receipt. The MailMessage class DeliveryNotificationOptions Enumeration property describes the delivery notification options for an email. To request a read receipt after sending an email, follow these steps:

  1. Create an instance of the MailMessage class.
  2. Specify the sender, receiver and HTML body for the email in the MailMessage instance.
  3. Specify the DeliveryNotificationOptions in other MailMessage instances.
  4. Create an instance of the SmtpClient class and send the email using the Send method.

Read receipt requests may not be always honored because:

  • A mail client may not implement that functionality.
  • The end-user may have that functionality turned off.
  • The end-user may choose not to send one.

The following code snippet shows you how to request a read receipt.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create an Instance of MailMessage class
MailMessage message = new MailMessage();
// Specify From, To, HtmlBody, DeliveryNotificationOptions field
message.From = "sender@sender.com";
message.To.Add("receiver@receiver.com");
message.HtmlBody = "<html><body>This is the Html body</body></html>";
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
message.Headers.Add("Return-Receipt-To", "sender@sender.com");
message.Headers.Add("Disposition-Notification-To", "sender@sender.com");
// Create an instance of SmtpClient Class
SmtpClient client = new SmtpClient();
// Specify your mailing host server, Username, Password and Port No
client.Host = "smtp.server.com";
client.Username = "Username";
client.Password = "Password";
client.Port = 25;
try
{
// Client.Send will send this message
client.Send(message);
// Display ‘Message Sent’, only if message sent successfully
Console.WriteLine("Message sent");
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(ex.ToString());
}

Set Email Headers

Email headers represent an Internet standard and RFC define header fields which are included in Internet email messages. An email header can be specified using the MailMessage class. Common header types are defined in the HeaderType class. It is a sealed class working as a normal enumeration.

Normally an email header contains these fields:

  • To: Recipient addresses can be specified in the To field. The To field recipients are the message’s primary audience. There can be more than one recipient addresses.
  • From: This field presents the email address of the message sender.
  • Cc: Allows users to send a message as a “Carbon Copy” or “Courtesy Copy”. That is, the receiver is not expected to reply or act. Typically, supervisory personnel are notified with CC.
  • Bcc: It stands for Blind Carbon Copy, which lets you send an email to a recipient that is hidden from other recipients.
  • ReplyTo: This header field is meant to indicate where the sender wants replies to go.
  • Subject: Title, heading, subject. Often used as a thread indicator for messages replying to or commenting on other messages.
  • Date: This header specifies a date (and time). Normally this is the date at which the message was composed and sent.
  • XMailer: Information about the client software of the originator. Example: X-Mailer: Aspose.Email XMailer is used by mail clients. Different mail clients will have different XMailer values. MS Outlook’s XMailer value is Microsoft Office Outlook, Build 11.0.5510. It is ignored by the email receiver or email reader.

Normally, an email header looks something like this:


 Reply-To: reply@reply.com

From: sender@sender.com

To: guangzhou@guangzhoo.com

Subject: test mail

Date: 6 Mar 2006 8:2:2 +0800

X-Mailer: Aspose.Email

To customize an email header, follow these steps:

  • Create an instance of the MailMessage class.
  • Specify To, From, Cc, Bcc, ReplyTo, Subject, Date & XMailer using an instance of the MailMessage.
  • Create an instance of the MimeHeader class and specify the secret header.
  • Add the secret header to the MailMessage instance.

The following code snippet shows you how to set email headers.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
// Create an instance MailMessage class
MailMessage mailMessage = new MailMessage();
// Specify ReplyTo, From, To field, Cc and Bcc Addresses
mailMessage.ReplyToList.Add("reply@reply.com");
mailMessage.From = "sender@sender.com";
mailMessage.To.Add("receiver1@receiver.com");
mailMessage.CC.Add("receiver2@receiver.com");
mailMessage.Bcc.Add("receiver3@receiver.com");
// Specify Date, Message subject, XMailer, Secret Header, Save message to disc
mailMessage.Subject = "test mail";
mailMessage.Date = new System.DateTime(2006, 3, 6);
mailMessage.XMailer = "Aspose.Email";
mailMessage.Headers.Add("secret-header", "mystery");
mailMessage.Save(dataDir + "SetEmailHeaders_out.msg", SaveOptions.DefaultMsg);

The above code snippet produces an email header in the following format. This can be observed by opening the resultant file “MsgHeaders.msg” in Microsoft Outlook and then view the Properties.


 Reply-To: reply@reply.com

From: sender@sender.com

To: receiver1@receiver.com

CC: receiver2@receiver.com

BCC: receiver3@receiver.com

Subject: test mail

Date: 6 Mar 2006 8:2:2 +0800

X-Mailer: Aspose.Email

secret-header: mystery

Insert Header at Specific Location

The Add method of HeadersCollection class inserts the header at the end of the collection. However, it may sometimes be necessary to insert a header at a specific location. In such a case, the Add method won’t be of help. To achieve this, use the Insert method of the HeadersCollection. If the collection contains headers with the same name, this header will be inserted before other headers with the same name. The following code snippet shows you how to insert header at a specific location.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Insert Header at Specific Location
MailMessage emailMessage = MailMessage.Load(fileName);
emailMessage.Headers.Insert("Received", "Value");

Adding Custom headers to email

The programming sample below demonstrates how to specify a custom header in an email message. An email header can be specified using the MailMessage class. To specify a custom header in an email message, please follow these steps:

  1. Create an instance of the MailMessage class.
  2. Specify the to, from and subject values using the MailMessage instance.
  3. Add the secret header into the MailMessage instance.
  4. Create an instance of the SmtpClient class and send the email using the Send method.

The following code snippet shows you how to add custom headers to email.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create an instance of the MailMessage class
MailMessage message = new MailMessage();
// Specify ReplyTo, from, To, Message subject and secret header field
message.ReplyToList.Add("reply@reply.com");
message.From = "sender@sender.com";
message.To.Add("receiver1@receiver.com");
message.Subject = "test mail";
message.Headers.Add("secret-header", "mystery");
// Create an instance of the SmtpClient Class
SmtpClient client = new SmtpClient();
// Specify your mailing host server, Username, Password, Port
client.Host = "smtp.server.com";
client.Username = "Username";
client.Password = "Password";
client.Port = 25;
try
{
// Client.Send will send this message
client.Send(message);
Console.WriteLine("Message sent");
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(ex.ToString());
}

Sign Emails with DKIM

Aspose.Email allows signing Email with DKIM (DomainKeys Identified Mail). This lets an organization take responsibility for a message that is in transit (More Info). DKIM adds a digital signature to the email message headers that can be validated by recipients. The public key of the sender enables the receiver to verify that the signature matches the message’s contents. The DKIMSign method of the MailMessage class is used to set the cryptographic and signature information for signing the message. The following code snippet shows you how to sign emails with DKIM.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
string privateKeyFile = Path.Combine(RunExamples.GetDataDir_SMTP().Replace("_Send", string.Empty), RunExamples.GetDataDir_SMTP()+ "key2.pem");
RSACryptoServiceProvider rsa = PemReader.GetPrivateKey(privateKeyFile);
DKIMSignatureInfo signInfo = new DKIMSignatureInfo("test", "yandex.ru");
signInfo.Headers.Add("From");
signInfo.Headers.Add("Subject");
MailMessage mailMessage = new MailMessage("useremail@gmail.com", "test@gmail.com");
mailMessage.Subject = "Signed DKIM message text body";
mailMessage.Body = "This is a text body signed DKIM message";
MailMessage signedMsg = mailMessage.DKIMSign(rsa, signInfo);
try
{
SmtpClient client = new SmtpClient("smtp.gmail.com", 587, "your.email@gmail.com", "your.password");
client.Send(signedMsg);
}
finally
{}

See Also

This article also covers these topics. The codes are same as above.

Category: Email Body Encoding

Category: Send Email