Specify different port for POP3, SMTP or IMAP

Establishing IMAP, POP3 or SMTP connection with Mail.dll email component using a default port is easy:

// C#

client.Connect("mail.example.com");

' VB.NET

client.Connect("mail.example.com")

If you need to specify different port just use overloaded version of Connect method:

// C#

client.Connect("mail.example.com", 999);
// -or-
client.Connect("mail.example.com", 999, false);

' VB.NET

client.Connect("mail.example.com", 999)
' -or-
client.Connect("mail.example.com", 999, False)

If you are using SSL/TLS:

// C#

client.ConnectSSL("mail.example.com", 999);
// -or-
client.Connect("mail.example.com", 999, true);

' VB.NET

client.ConnectSSL("mail.example.com", 999)
' -or-
client.Connect("mail.example.com", 999, True)

Check out the difference between implicit and explicit SSL/TLS modes.

Forward an email as an attachment

If you want to share an email with other parties, forwarding it works like a charm in Mail.dll.

There are two ways of forwarding a message:

In this article we’ll describe the second option, in which you add forwarded an email as an attachment appended to your forward. This lets you forward multiple emails in one go too.

Why forward as an attachment?

Forwarding as an attachment is a way to share the email body in exactly the form you received it. This makes it easier for the recipient of your forward to reply to the original sender and it preserves some message details that can otherwise be lost — useful to help troubleshooting email problems, for example.

Forwarding an email

In our example we’ll use Mail.dll .NET IMAP component to download first message from an IMAP server. Then we’ll create new message and we’ll add previously received email as an attachment to it. Finally we’ll use Mail.dll SMTP client to send this message.

Please note that we are using MimeFactory class to create MIME object with content type set to mime-rfc822. This content type is specially designed for attaching email messages.

// C# version

byte[] eml = GetFirstMessage();

MailBuilder builder = new MailBuilder();
builder.From.Add(new MailBox("from@example.com"));
builder.To.Add(new MailBox("forward_address@example.com"));
builder.Subject = "Forwarded email is attached";

// attach the message
MimeRfc822 rfc822 = new MimeFactory().CreateMimeRfc822();
rfc822.Data = eml;

builder.AddAttachment(rfc822);

IMail forward = builder.Create();

using (Smtp smtp = new Smtp())
{
    smtp.Connect("smtp.example.com"); // or ConnectSSL if you want to use SSL
    smtp.UseBestLogin("user", "password");
    smtp.SendMessage(forward);
    smtp.Close();
}


static byte[] GetFirstMessage()
{
    byte[] eml;
    using (Imap imap = new Imap())
    {
        imap.Connect("imap.example.com"); // or ConnectSSL if you want to use SSL
        imap.UseBestLogin("user", "password");

        // Receive first message
        List<long> uids = imap.GetAll();
        if (uids.Count == 0)
            throw new Exception("There are no messages");
        eml = imap.GetMessageByUID(uids[0]);
        imap.Close();
    }
    return eml;
}
' VB.NET version

Dim eml As Byte()= GetFirstMessage()

Dim builder As New MailBuilder()
builder.From.Add(New MailBox("from@example.com"))
builder.[To].Add(New MailBox("forward_address@example.com"))
builder.Subject = "Forwarded email is attached"

' attach the message
Dim rfc822 As MimeRfc822 = New MimeFactory().CreateMimeRfc822()
rfc822.Data = eml

builder.AddAttachment(rfc822)

Dim forward As IMail = builder.Create()

Using smtp As New Smtp()
    smtp.Connect("smtp.example.com") ' or ConnectSSL if you want to use SSL
    smtp.UseBestLogin("user", "password")
    smtp.SendMessage(forward)
    smtp.Close()
End Using


Private Function GetFirstMessage() As Byte()
    Dim eml As Byte()
    Using imap As New Imap()
        imap.Connect("imap.example.com") ' or ConnectSSL if you want to use SSL
        imap.UseBestLogin("user", "password")

        ' Receive first message
        Dim uids As List(Of Long) = imap.GetAll()
        If uids.Count = 0 Then
            Throw New Exception("There are no messages")
        End If
        eml = imap.GetMessageByUID(uids(0))
        imap.Close()
    End Using
    Return eml
End Function

Forwarding an email saved to disk

If your original message is already saved on disk. You can use AddAttachment method. It will automatically choose correct content-type using the file’s extension (.eml).

// C#

MailBuilder builder = new MailBuilder();
builder.From.Add(new MailBox("bob@example.com", "Bob"));
builder.To.Add(new MailBox("alice@example.com", "Alice"));
builder.Subject = "Forwarded message";
builder.Text = "Forwarded message is attached.";

builder.AddAttachment("original.eml");

IMail forward = builder.Create();
' VB.NET

Dim builder As New MailBuilder()
builder.From.Add(New MailBox("bob@example.com", "Bob"))
builder.[To].Add(New MailBox("alice@example.com", "Alice"))
builder.Subject = "Forwarded message"
builder.Text = "Forwarded message is attached."

builder.AddAttachment("original.eml")

Dim forward As IMail = builder.Create()

Access custom email header using IMAP

Most common email headers like From, Subject, Date, To, Cc etc. are exposed by IMail interface as properties. Those properties contain parsed information and return strong typed objects like DateTime‘s, string collections, MailAddress collections.

There are times however that you need to access non-standard email header. Good example is a need to get a spam value that your IMAP server assigns to every email by inserting additional ‘x-spam’ header.

Mail.dll MIME and S/MIME parser allows users to access entire MIME tree of the message. IMail.Document property returns MIME document that represent this email message. You can use IMail.Document.Root.Headers collection to access any non-standard and standard header.

If you are using IMAP client you can also search IMAP server for messages that have specified header or have specified value in header.

If you only need to access email headers, consider using GetHeadersByUID method, which doesn’t download entire message from IMAP server just headers. The sample below on the other hand downloads entire message.

// C# version

using System;
using Limilabs.Mail;
using Limilabs.Client.IMAP;

class Program
{
    static void Main(string[] args)
    {
        using (Imap imap = new Imap())
        {
            imap.Connect("imap.example.com");    // or ConnectSSL for SSL
            imap.Login("user", "password");

            MailBuilder builder = new MailBuilder();
            foreach (long uid in imap.GetAll())
            {
                var eml = imap.GetMessageByUID(uid);
                IMail email = builder.CreateFromEml(eml);
                Console.WriteLine("subject: {0}", email.Subject);

                // Get custom header:
                string header = email.Document.Root.Headers["x-spam"];
                Console.WriteLine("x-spam: {0}", header);
            }
            imap.Close();
        }
    }
};
' VB.NET version

Imports System
Imports Limilabs.Mail
Imports Limilabs.Client.IMAP

Public Module Module1
    Public Sub Main(ByVal args As String())

        Using imap As New Imap()
            imap.Connect("imap.example.com")    ' or ConnectSSL for SSL
            imap.Login("user", "password")

            Dim builder As New MailBuilder()
            For Each uid As String In imap.GetAll()
                Dim eml = imap.GetMessageByUID(uid)
                Dim email As IMail = builder.CreateFromEml(eml)
                Console.WriteLine("subject: {0}", email.Subject)

                ' Get custom header:
                Dim header As String = email.Document.Root.Headers("x-spam")
                Console.WriteLine("x-spam: {0}", header)
            Next
            imap.Close()
        End Using

    End Sub
End Module

Send email

This article describes how to create and send email message using Mail.dll .NET email library.

As a prerequisite you need to add reference to Mail.dll to your project. Please check MSDN how to add reference article for details.

When your reference is added you need to import appropriate namespaces both for email handling and SMTP component:

// C#

using Limilabs.Mail;
using Limilabs.Mail.Headers;
using Limilabs.Client.SMTP;
' VB

Imports Limilabs.Mail
Imports Limilabs.Mail.Headers
Imports Limilabs.Client.SMTP

First thing you need to do is to create email message. You can use MailBuilder class for that. We’ll add add from and to addresses, set subject and plain text email content. We could also set Html property to create HTML email. Mail.dll automatically generates Message-ID and Date headers.

// C#

MailBuilder builder = new MailBuilder();
builder.From.Add(new MailBox("alice@mail.com", "Alice"));
builder.To.Add(new MailBox("bob@mail.com", "Bob"));
builder.Subject = "Test";
builder.Text = "This is plain text message.";

IMail email = builder.Create();
' VB

Dim builder As New MailBuilder()
builder.From.Add(New MailBox("alice@mail.com", "Alice"))
builder.[To].Add(New MailBox("bob@mail.com", "Bob"))
builder.Subject = "Test"
builder.Text = "This is plain text message."

Next step is to connect to your SMTP server and send your message. Use Connect(string host) method to establish connection. Typically SMTP server is working on port 587. You can use Connect(string host, int port) overload when you need to specify different port (for example 25). If your server requires SSL use ConnectSSL method (Here you can find more info on using SMTP with SSL).

// C#

using (Smtp smtp = new Smtp())
{
    smtp.Connect("server.example.com");    // or ConnectSSL for SSL
    smtp.UseBestLogin("user", "password"); // remove if authentication is not needed

    ISendMessageResult result = smtp.SendMessage(email);
    if (result.Status == SendMessageStatus.Success)
    {
        // Message was sent.
    }

    smtp.Close();
}
' VB

Using smtp As New Smtp()
    smtp.Connect("server.example.com")      ' or ConnectSSL for SSL
    smtp.UseBestLogin("user", "password")   ' remove if authentication is not needed

    Dim result As ISendMessageResult = smtp.SendMessage(email)

    If result.Status = SendMessageStatus.Success Then
        ' Message was sent.        
    End If

    smtp.Close()
End Using

Here are the full samples:

// C# version

using Limilabs.Mail;
using Limilabs.Mail.Headers;
using Limilabs.Client.SMTP;

class Program
{
    static void Main(string[] args)
    {
        // Use builder class to create new email
        MailBuilder builder = new MailBuilder();
        builder.From.Add(new MailBox("alice@mail.com", "Alice"));
        builder.To.Add(new MailBox("bob@mail.com", "Bob"));
        builder.Subject = "Test";
        builder.Text = "This is plain text message.";

        IMail email = builder.Create();

        // Send the message
        using (Smtp smtp = new Smtp())
        {
            smtp.Connect("server.example.com");    // or ConnectSSL for SSL
            smtp.UseBestLogin("user", "password"); // remove if not needed

            ISendMessageResult result = smtp.SendMessage(email);
            if (result.Status == SendMessageStatus.Success)
            {
                // Message was sent.
            }

            smtp.Close();
        }
    }
};
' VB.NET version

Imports Limilabs.Mail
Imports Limilabs.Mail.Headers
Imports Limilabs.Client.SMTP

Public Module Module1
    Public Sub Main(ByVal args As String())

        ' Use builder class to create new email
        Dim builder As New MailBuilder()
        builder.From.Add(New MailBox("alice@mail.com", "Alice"))
        builder.[To].Add(New MailBox("bob@mail.com", "Bob"))
        builder.Subject = "Test"
        builder.Text = "This is plain text message."

        Dim email As IMail = builder.Create()

        ' Send the message
        Using smtp As New Smtp()
            smtp.Connect("server.example.com")      ' or ConnectSSL for SSL
            smtp.UseBestLogin("user", "password")   ' remove if not needed

            Dim result As ISendMessageResult = smtp.SendMessage(email)

            If result.Status = SendMessageStatus.Success Then
                ' Message was sent.        
            End If

            smtp.Close()
        End Using

    End Sub
End Module

Please note that some error handling is missing for simplicity and you should examine ISendMessageResult result object returned by SendMessage method to be sure that email sending was successful.

Use TLS/SSL with SMTP in .NET

Mail.dll SMTP .NET email component supports Secure Socket Layer (SSL) and Transport Layer Security (TLS) protocols to authenticate the server and secure client-server email sending.

There are two modes in which Mail.dll can work:

  • Implicit – where Mail.dll SMTP client immediately connects using secure channel,
  • Explicit – where Mail.dll SMTP client connects on unsecured channel first and then secures the communication by issuing STARTTLS command. This mode is sometimes called TLS.

In both cases, by default, Secure Sockets Layer (SSL) 3.0 and Transport Layer Security (TLS) 1.0, 1.1, 1.2, 1.3 are acceptable for secure communication. You can change the defaults using Smtp.SSLConfiguration property.

Smtp client may decide to secure the channel, if SMTP server explicitly forbids logging-in on unsecured channel and you are using UseBestLogin method.

Here you can find more details on SSL vs TLS vs STARTTLS.

SMTP implicit TLS/SSL mode

Mail.dll SMTP component connects using secure TLS/SSL channel. You need to know in advance if, the server supports TLS/SSL connections – ask your administrator. Typically, SMTP over TLS/SSL is associated with port 465, but this is not always the case. You can always specify different, then standard port, using ConnectSSL method overload.

// C# version

using Limilabs.Mail;
using Limilabs.Client.POP3;

class Program
{
    static void Main(string[] args)
    {
        using (Smtp smtp = new Smtp())
        {
            smtp.ConnectSSL("mail.example.com");

            smtp.UseBestLogin("user", "password");

            MailBuilder builder = new MailBuilder();
            builder.Text = "text";
            builder.From.Add(new MailBox("from@example.com"));
            builder.To.Add(new MailBox("to@example.com"));

            IMail email = builder.Create();

            smtp.SendMessage(email);

            smtp.Close();
        }
    }
};
' VB.NET version

Imports Limilabs.Mail
Imports Limilabs.Client.SMTP

Public Module Module1
    Public Sub Main(ByVal args As String())

        Using smtp As New Smtp()

            smtp.ConnectSSL("mail.example.com")

            smtp.UseBestLogin("user", "password")

            Dim builder As New MailBuilder()
            builder.Text = "text"
            builder.From.Add(New MailBox("from@example.com"))
            builder.[To].Add(New MailBox("to@example.com"))

            Dim email As IMail = builder.Create()

            smtp.SendMessage(email)

            smtp.Close()
        End Using

    End Sub
End Module

SMTP explicit TLS/SSL mode

Mail.dll SMTP component connects using clear text channel and secures the channel using TLS/SSL by issuing STARTTLS command. Typically standard SMTP ports: 25 or 587 are used, but this is not always the case. You can always specify different then standard port using Connect method overloads. By default 587 port is used.

// C# version

using Limilabs.Mail;
using Limilabs.Mail.Headers;
using Limilabs.Client.SMTP;

class Program
{
    static void Main(string[] args)
    {
        using (Smtp smtp = new Smtp())
        {
            smtp.Connect("mail.example.com");

            smtp.StartTLS();

            smtp.UseBestLogin("user", "password");

            MailBuilder builder = new MailBuilder();
            builder.Text = "text";
            builder.From.Add(new MailBox("from@example.com"));
            builder.To.Add(new MailBox("to@example.com"));

            IMail email = builder.Create();

            smtp.SendMessage(email);

            smtp.Close();
        }
    }
};
' VB.NET version

Imports Limilabs.Mail
Imports Limilabs.Mail.Headers
Imports Limilabs.Client.SMTP

Public Module Module1
    Public Sub Main(ByVal args As String())

        Using smtp As New Smtp()
            smtp.Connect("mail.example.com")

            smtp.StartTLS()

            smtp.UseBestLogin("user", "password")

            Dim builder As New MailBuilder()
            builder.Text = "text"
            builder.From.Add(New MailBox("from@example.com"))
            builder.[To].Add(New MailBox("to@example.com"))

            Dim email As IMail = builder.Create()

            smtp.SendMessage(email)

            smtp.Close()
        End Using

    End Sub
End Module

After you connect, you can check, if your SMTP server supports explicit TLS/SSL using following code:

// C# version

bool supportsStartTLS = smtp.SupportedExtensions()
   .Contains(SmtpExtension.StartTLS);
' VB.NET version

Dim supportsStartTLS As Boolean = smtp.SupportedExtensions() _
   .Contains(SmtpExtension.StartTLS)

You can read more here on how to know which extensions does your server support.

Self-signed certificates

If you are using self-signed certificates you may encounter this error: The remote certificate is invalid according to the validation procedure.


Get Mail.dll