Mail Features

Create Message

There are two type of mail message: MIME and Non-MIME. It's recommended to create mail messages in MIME format since most email clients today are MIME compatible. This section illustrates how to create mail messages.

Create a simple message

In order to use the classes in the Ultimate Mail library, you have to add references to ComponentPro.Mail.dll, ComponentPro.Common.dll, and ComponentPro.Network.dll assemblies to your project.

The examples below show how to create a simple mail message using the UltimateMail component:

// Create a new instance of the MailMessage class.
MailMessage msg = new MailMessage();

msg.From.Add("john@somedomain.com");
msg.To.Add("someone@somedomain.com");
msg.Subject = "Hello";
msg.BodyText = "How are you?";
' Create a new instance of the MailMessage class.
Dim msg As New MailMessage()

msg.From.Add("john@somedomain.com")
msg.To.Add("someone@somedomain.com")
msg.Subject = "Hello"
msg.BodyText = "How are you?"
// Create a new instance of the MailMessage class.
MailMessage msg = new MailMessage();

msg.From.Add("john@somedomain.com");
msg.To.Add("someone@somedomain.com");
msg.Subject = "Hello";
msg.BodyText = "How are you?";

// Load a certificate file and encrypt the message.
msg.Encrypt(new X509Certificate2("mycert.cer", "mypassword"));
' Create a new instance of the MailMessage class.
Dim msg As New MailMessage()

msg.From.Add("john@somedomain.com")
msg.To.Add("someone@somedomain.com")
msg.Subject = "Hello"
msg.BodyText = "How are you?"

' Load a certificate file and encrypt the message.
msg.Encrypt(New X509Certificate2("mycert.cer", "mypassword"))

Create an encrypted mail message

To encrypt a mail message, you only need an X509 certificate (private key is not required). Certificate can be loaded from a certificate file (.cer or .der extensions), from a PKCS#12 encrypted file (.pfx or .p12 extensions), or get it from the Window Certificate Store.

Only the message body is encrypted, the top-level headers are not encrypted.The example below shows how to encrypt a mail message.

Create an encrypted and signed mail message

A message can be both encrypted and signed. This ensures to the sender that only the intended recipients are able to read the message content, and to the recipient that the message was indeed sent by the sender.

There are two ways to produce a message that is both encrypted and sign:

  • Sign the message first, then encrypt the signed message.
  • Encrypt the message first, then sign the encrypted message.

In the first case, no one but the recipient will be able to validate the signature and access the message content. In the second case, no one but the recipient will be able to access the message content, but anyone will be able to validate the signature. Both ways have their pros and cons, but there is a very strong reason to prefer the first way: Outlook Express does not handle the second way correctly, and reports the correct signature is not valid.

// Create a new instance of the MailMessage class.
MailMessage msg = new MailMessage();

msg.From.Add("john@somedomain.com");
msg.To.Add("someone@somedomain.com");
msg.Subject = "Hello";
msg.BodyText = "How are you?";

// Load a certificate file and sign the message.
msg.Sign(new X509Certificate2("mycert.pfx", "mypassword"));

// Load a certificate file and encrypt the message.
msg.Encrypt(new X509Certificate2("mycert.cer", "mypassword"));
' Create a new instance of the MailMessage class.
Dim msg As New MailMessage()

msg.From.Add("john@somedomain.com")
msg.To.Add("someone@somedomain.com")
msg.Subject = "Hello"
msg.BodyText = "How are you?"

' Load a certificate file and sign the message.
msg.Sign(New X509Certificate2("mycert.pfx", "mypassword"))

' Load a certificate file and encrypt the message.
msg.Encrypt(New X509Certificate2("mycert.cer", "mypassword"))
// Create a new instance of the MailMessage class.
MailMessage msg = new MailMessage();

// Add from address.
msg.From.Add("fromemail@domain.com");
// Add recipient.
msg.To.Add("fromemail@domain.com");
// Set subject.
msg.Subject = "MHT message";
// ImageTypeName's src is linked to an embedded image.
msg.BodyHtml = "Below is an attached image:<br><img src='cid:myimage'>";
// Create a LinkedResource object.
LinkedResource lr = new LinkedResource("c:\\myfolder\\myimage.jpg", MediaTypeNames.Image.Jpeg);
lr.ContentIdentifier = "myimage";
msg.LinkedResources.Add(lr);

// Connect, login and send the message here.
// the following code demonstrates how to do that:
Smtp client = new Smtp();
client.Connect("servername");
client.Authenticate("username", "password");
client.Send(msg);
client.Disconnect();

// ...
' Create a new instance of the MailMessage class.
Dim msg As New MailMessage()

' Add from address.
msg.From.Add("fromemail@domain.com")
' Add recipient.
msg.To.Add("fromemail@domain.com")
' Set subject.
msg.Subject = "MHT message"
' ImageTypeName's src is linked to an embedded image.
msg.BodyHtml = "Below is an attached image:<br><img src='cid:myimage'>"
' Create a LinkedResource object.
Dim lr As New LinkedResource("c:\myfolder\myimage.jpg", MediaTypeNames.Image.Jpeg)
lr.ContentIdentifier = "myimage"
msg.LinkedResources.Add(lr)

' Connect, login and send the message here.
' the following code demonstrates how to do that:
Dim client As New Smtp()
client.Connect("servername")
client.Authenticate("username", "password")
client.Send(msg)
client.Disconnect()

' ...

Create an e-mail message containing embedded resources

The code snippet below shows you how to create an e-mail message and add an image from local disk as a LinkedResource object:

Create a message that has read receipt request

It is often needed to make sure recipients received your email. This task can easily be done by adding addresses that will receive the notification to your message using the Headers property of the MailMessage class.

// Create a new instance of the MailMessage class.
MailMessage msg = new MailMessage();

msg.From.Add("john@somedomain.com");
msg.To.Add("someone@somedomain.com");
msg.Subject = "Hello";
msg.BodyText = "How are you?";
msg.Headers.Add("Disposition-Notification-To", "john@somedomain.com");

// And Send it
Smtp client = new Smtp();

// Connect and authenticate to your server here.

// ...
client.Send(msg);

// ...
' Create a new instance of the MailMessage class.
Dim msg As New MailMessage()

msg.From.Add("john@somedomain.com")
msg.To.Add("someone@somedomain.com")
msg.Subject = "Hello"
msg.BodyText = "How are you?"
msg.Headers.Add("Disposition-Notification-To", "john@somedomain.com")

' And Send it
Dim client As New Smtp()

' Connect and authenticate to your server here.

' ...
client.Send(msg)

' ...
MailMessage orgMsg = new MailMessage();

// ...

// Create a new instance of the MailMessage class.
MailMessage msg = new MailMessage();

msg.From.Add("john@somedomain.com");
msg.To.Add("someone@somedomain.com");
msg.Subject =  "RE: " + orgMsg.Subject;
msg.BodyText = "How are you?";

// ...
Dim orgMsg As New MailMessage()

' ...

' Create a new instance of the MailMessage class.
Dim msg As New MailMessage()

msg.From.Add("john@somedomain.com")
msg.To.Add("someone@somedomain.com")
msg.Subject = "RE: " & orgMsg.Subject
msg.BodyText = "How are you?"

' ...

Create a reply message

To reply to a message, you can simply create a new message object including the subject of the original message with 'RE: ' placed at the beginning. The following code example shows you how to do that.

Include original message as attachment

To include the original message as an attachment, simply create a new Attachment object containing the original message and add it to a new message. The following code example shows you how to do that.

MailMessage orgMsg = new MailMessage();

// ...

// Create a new instance of the MailMessage class.
MailMessage msg = new MailMessage();

msg.From.Add("john@somedomain.com");
msg.To.Add("someone@somedomain.com");
msg.Subject =  "FW: " + orgMsg.Subject;
msg.BodyText = "How are you?";

Attachment attachment = new Attachment(orgMsg);
msg.Attachments.Add(attachment);

// ...
Dim orgMsg As New MailMessage()

' ...

' Create a new instance of the MailMessage class.
Dim msg As New MailMessage()

msg.From.Add("john@somedomain.com")
msg.To.Add("someone@somedomain.com")
msg.Subject = "FW: " & orgMsg.Subject
msg.BodyText = "How are you?"

Dim attachment As New Attachment(orgMsg)
msg.Attachments.Add(attachment)

' ...

Load and Save message

Ultimate Mail lets you load and save mail messages easily.

Load an existing message

With UltimateMail component, you can quickly create a new message from many sources such as from local disk file or data stream. The following sample illustrates how to create load an existing message (.EML). From version 5.0, Ultimate Mail can also load Outlook MSG file format.

// Create a new instance of the MailMessage class.
MailMessage msg = new MailMessage("c:\\temp\\my message.eml");

// ...

// Add recipient to it.
msg.To.Add("someone@somedomain.com");

// ...

// Load an Outlook MSG file
msg = new MailMessage("c:\\temp\\my outlook message.msg");
msg.Subject += " - Test";
' Create a new instance of the MailMessage class.
Dim msg As New MailMessage("c:\temp\my message.eml")

' ...

' Add recipient to it.
msg.To.Add("someone@somedomain.com")

' ...

' Load an Outlook MSG file
msg = New MailMessage("c:\temp\my outlook message.msg")
msg.Subject &= " - Test"
// Create a new instance of the MailMessage class.
MailMessage msg = new MailMessage();

msg.From.Add("john@somedomain.com");
msg.To.Add("someone@somedomain.com");
msg.Subject = "Hello";
msg.BodyText = "How are you?";

// ...

// Save the message.
msg.Save("c:\\temp\\my message.eml");
' Create a new instance of the MailMessage class.
Dim msg As New MailMessage()

msg.From.Add("john@somedomain.com")
msg.To.Add("someone@somedomain.com")
msg.Subject = "Hello"
msg.BodyText = "How are you?"

' ...

' Save the message.
msg.Save("c:\temp\my message.eml")

Saving a message

MailMessage class provides a set of convenient methods for saving a message to either a local file or write it into a data stream. The following example shows you how to create a new mail message and save it to a local file:

Extract attachments from a message

Attachments in a mail message can either be extracted to file or stream object. The example below shows how to load a mail message and save its attachments to disk:

/// <summary>
/// Extracs attachments from a mail file.
/// </summary>
/// <param name="fileName">Mail file name.</param>
/// <returns>A boolean value indicating whether the extraction is successful.</returns>
private static bool ExtractAttachments(string fileName)
{
    try
    {
        // Load the mail message from disk
        MailMessage mail = new MailMessage();
        mail.Load(fileName);

        // DecryptData the message if it is encrypted
        if (mail.IsEncrypted)
        {
            if (!mail.Decryptable)
            {
                Console.WriteLine("Message cannot be decrypted. You do not have the private key.");
                return false;
            }
            mail.Decrypt();
        }

        // ValidateRequest the signature if the message is signed
        if (mail.IsSigned)
        {
            MailSignatureValidationResult result = mail.ValidateSignature();
            if (result.Valid)
            {
                Console.WriteLine("The message is signed and the signature is valid.");
            }
            else
            {
                Console.WriteLine("The message is signed, but the signature is not valid.");                        
            }
        }

        Console.WriteLine("Message contains {0} attachments.", mail.Attachments.Count);

        // If message has no attachments, just exit
        if (mail.Attachments.Count == 0)
            return false;

        foreach (Attachment attachment in mail.Attachments)
        {
            // Write the file
            Console.WriteLine("Saving '{0}' ({1}).", attachment.FileName, attachment.MediaType);
            attachment.Save(attachment.FileName);
        }

        return true;
    }
    catch (Exception exc)
    {
        Console.WriteLine("An error occurred: {0}", exc.Message);
    }

    return false;
}
''' <summary>
''' Extracs attachments from a mail file.
''' </summary>
''' <param name="fileName">Mail file name.</param>
''' <returns>A boolean value indicating whether the extraction is successful.</returns>
Private Shared Function ExtractAttachments(ByVal fileName As String) As Boolean
    Try
        ' Load the mail message from disk
        Dim mail As New MailMessage()
        mail.Load(fileName)

        ' DecryptData the message if it is encrypted
        If mail.IsEncrypted Then
            If Not mail.Decryptable Then
                Console.WriteLine("Message cannot be decrypted. You do not have the private key.")
                Return False
            End If
            mail.Decrypt()
        End If

        ' ValidateRequest the signature if the message is signed
        If mail.IsSigned Then
            Dim result As MailSignatureValidationResult = mail.ValidateSignature()
            If result.Valid Then
                Console.WriteLine("The message is signed and the signature is valid.")
            Else
                Console.WriteLine("The message is signed, but the signature is not valid.")
            End If
        End If

        Console.WriteLine("Message contains {0} attachments.", mail.Attachments.Count)

        ' If message has no attachments, just exit
        If mail.Attachments.Count = 0 Then
            Return False
        End If

        For Each attachment As Attachment In mail.Attachments
            ' Write the file
            Console.WriteLine("Saving '{0}' ({1}).", attachment.FileName, attachment.MediaType)
            attachment.Save(attachment.FileName)
        Next attachment

        Return True
    Catch exc As Exception
        Console.WriteLine("An error occurred: {0}", exc.Message)
    End Try

    Return False
End Function
// Create a new instance of the MailMessage class.
MailMessage msg = new MailMessage();
msg.Load("c:\\temp\\mymessage.eml");

// Extract embedded resources.
foreach (LinkedResource lr in msg.LinkedResources)
{
    lr.Save("c:\\temp\\resources\\" + lr.ContentIdentifier.Id);
}
' Create a new instance of the MailMessage class.
Dim msg As New MailMessage()
msg.Load("c:\temp\mymessage.eml")

' Extract embedded resources.
For Each lr As LinkedResource In msg.LinkedResources
    lr.Save("c:\temp\resources\" & lr.ContentIdentifier.Id)
Next lr

Extracting embedded resources

Linked resources in a mail message can either be extracted to file or stream object. The example below shows how to load a mail message and save its embedded resources to disk:

Encryption and Decryption

Ultimate Mail lets you encrypt and decrypt mail messages easily.

Encrypt a mail message

To encrypt a mail message, you need to provide a key or certificate for the encryption and call the Encrypt method of the MailMessage. See the example below for more details:

// Create a new instance of the MailMessage class.
MailMessage msg = new MailMessage();

// Load an outlook message
msg.Load("message.msg");

// Load a certificate file and encrypt the message.
msg.Encrypt(new X509Certificate2("mycert.cer", "mypassword"));

msg.Save("encrypted_message.msg", MailFormat.OutlookMsg);
Unable to read code file 'C:\ComponentPro\Website2.0\Sites\ComponentPro\CodeExamples\Mail\VB\MailEncryptLoaded.vb'.
// Create a new instance of the MailMessage class.
MailMessage msg = new MailMessage();

// Load the message from a file.
msg.Load("testmessage.eml");

// Check to see whether the message is encrypted or not.
if (msg.IsEncrypted)
{
    if (!msg.Decryptable)
        throw new ApplicationException("The message cannot be decrypted.");

    msg.Decrypt();
}

// ...
' Create a new instance of the MailMessage class.
Dim msg As New MailMessage()

' Load the message from a file.
msg.Load("testmessage.eml")

' Check to see whether the message is encrypted or not.
If msg.IsEncrypted Then
    If Not msg.Decryptable Then
        Throw New ApplicationException("The message cannot be decrypted.")
    End If

    msg.Decrypt()
End If

' ...

Decrypt an encrypted mail message

In order to access an encrypted message's content, you need to decrypt it first. To do that, you should check the message whether it can be decrypted or not, and then you can use the Decrypt method of the MailMessage to decrypt it. See the example below for more details:

Sign and Validate Mail Messages

Ultimate Mail lets you sign and validate mail messages easily.

Sign a mail message

To sign a mail message, call the Sign method of the MailMessage class as shown in this example:

// Create a new instance of the MailMessage class.
MailMessage msg = new MailMessage();

// Load an outlook message
msg.Load("message.msg");

// Load a certificate file and encrypt the message.
msg.Sign(new X509Certificate2("mycert.cer", "mypassword"));

msg.Save("signed_message.msg", MailFormat.OutlookMsg);
Unable to read code file 'C:\ComponentPro\Website2.0\Sites\ComponentPro\CodeExamples\Mail\VB\MailSignLoaded.vb'.
// Create a new instance of the MailMessage class.
MailMessage msg = new MailMessage();

// Load the message from a file.
msg.Load("testmessage.eml");

// Check to see whether the message is signed or not.
if (msg.IsSigned)
{
    MailSignatureValidationResult validationResult = msg.ValidateSignature();
    if (validationResult.Valid)
        Console.WriteLine("The signature is valid.");
    else
        Console.WriteLine("The signature is invalid.");
    msg.Decrypt();
}
else
    Console.WriteLine("The message is not signed.");

// ...
' Create a new instance of the MailMessage class.
Dim msg As New MailMessage()

' Load the message from a file.
msg.Load("testmessage.eml")

' Check to see whether the message is signed or not.
If msg.IsSigned Then
    Dim validationResult As MailSignatureValidationResult = msg.ValidateSignature()
    If validationResult.Valid Then
        Console.WriteLine("The signature is valid.")
    Else
        Console.WriteLine("The signature is invalid.")
    End If
    msg.Decrypt()
Else
    Console.WriteLine("The message is not signed.")
End If

' ...

Validate signatures

The signed mail message should be validated to make sure the message was composed by the signer. To accomplish this, you can call the ValidateSignature method of the MailMessage class. To ensure the message is signed or not, you can use the IsSigned property.

The following simple example shows you how to check a message to see whether it's signed or not, if it's signed we will validate the message's certificate:

Find appropriate certificate stores

Windows contains several built-in certificate stores that might already contain certificates and they are used by applications on the system such as Internet Explorer, Outlook,... These stores are per-user and can be managed by a MMC snap-in called "Certificates" or using Internet Explorer.

The following example illustrates how to open the user's personal certificate store and find certificates with the specified criteria:

// Open the user's personal certificate store.
X509Store store = new X509Store(StoreName.My);
// Read-only.
store.Open(OpenFlags.ReadOnly);

if (store.Certificates.Count > 0)
{
    foreach (X509Certificate2 item in store.Certificates)
    {
        if (item.SubjectName.Name.IndexOf("my name") != -1)
        {
            // Create a new instance of the MailMessage class.
            MailMessage msg = new MailMessage();

            msg.From.Add("john@somedomain.com");
            msg.To.Add("someone@somedomain.com");
            msg.Subject = "Hello";
            msg.BodyText = "How are you?";

            // Sign the message.
            msg.Sign(item);
        }
    }
}
' Open the user's personal certificate store.
Dim store As New X509Store(StoreName.My)
' Read-only.
store.Open(OpenFlags.ReadOnly)

If store.Certificates.Count > 0 Then
    For Each item As X509Certificate2 In store.Certificates
        If item.SubjectName.Name.IndexOf("my name") <> -1 Then
            ' Create a new instance of the MailMessage class.
            Dim msg As New MailMessage()

            msg.From.Add("john@somedomain.com")
            msg.To.Add("someone@somedomain.com")
            msg.Subject = "Hello"
            msg.BodyText = "How are you?"

            ' Sign the message.
            msg.Sign(item)
        End If
    Next item
End If