email component

EASendMail SMTP Component > Using EASendMail in C# .NET to send email

Send Email in C# Tutorial - SSL, HTML, Embedded Image, S/MIME

This page has moved. Click Here! to redirect to our new page.

Introduction

EASendMail is a SMTP component which supports all operations of SMTP/ESMTP protocols (RFC 821, RFC 822, RFC 2554). This tutorial covers everything of sending email with EASendMail in C#.

Installation

You should download the EASendMail SMTP Component Installer and install it on your machine at first.

Add Reference of EASendMail to Visual Stuido C#.NET Project

To use EASendMail SMTP Component in your project, the first step is "Add reference of EASendMail to your project". Please create/open your project with Visual Studio.NET, then choose menu->"Project"->"Add Reference"->".NET"->"Browse...", and choose the EASendMail{version}.dll from your disk, click "Open"->"OK", the reference of EASendMail will be added to your project, and you can start to use EASendMail to send email in your project.

c# email reference

Because EASendMail has separate builds for .Net Framework, please refer to the following table and choose the correct dll.

Separate builds of run-time assembly for .Net Framework 1.1, 2.0, 3.5, 4.0 and .Net Compact Framework 2.0, 3.5.

File .NET Framework Version
EASendMail.dll Built with .NET Framework 1.1
It requires .NET Framework 1.1, 2.0, 3.5 or later version.
EASendMail20.dll Built with .NET Framework 2.0
It requires .NET Framework 2.0, 3.5 or later version.
EASendMail35.dll Built with .NET Framework 3.5
It requires .NET Framework 3.5 or later version.
EASendMaill40.dll Built with .NET Framework 4.0
It requires .NET Framework 4.0 or later version.
EASendMailCF20.dll Built with .NET Compact Framework 2.0
It requires .NET Compact Framework 2.0, 3.5 or later version.
EASendMailCF35.dll Built with .NET Compact Framework 3.5
It requires .NET Compact Framework 3.5 or later version.

A simple email sending C# project

First of all, let's create a C# console project at first, then add the reference of EASendMail in your project (Please refer to previous section).

c# console email sample

Add the following code like this:

/*[C# Example - Send Simple Email]*/
using System;
using System.Collections.Generic;
using System.Text;
using EASendMail; //add EASendMail namespace

namespace mysendemail
{
    class Program
    {
        static void Main(string[] args)
        {
            SmtpMail oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();
        
            //Set sender email address, please change it to yours
            oMail.From = "test@emailarchitect.net";
            //Set recipient email address, please change it to yours
            oMail.To = "support@emailarchitect.net";
            //Set email subject
            oMail.Subject = "test email from c# project";
            //Set email body
            oMail.TextBody = "this is a test email sent from c# project, do not reply";

            //Your smtp server address
            SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");
            //User and password for ESMTP authentication, if your server doesn't require
            //User authentication, please remove the following codes.            
            oServer.User = "test@emailarchitect.net";
            oServer.Password = "testpassword";

            //If your smtp server requires SSL connection, please add this line
            //oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

            try
            {
                Console.WriteLine("start to send email ...");
                oSmtp.SendMail(oServer, oMail);
                Console.WriteLine("email was sent successfully!");
            }
            catch (Exception ep)
            {
                Console.WriteLine("failed to send email with the following error:");
                Console.WriteLine(ep.Message);
            }
        }
    }
}

If you set everything right, you can get "email was sent successfully". If you get "failed to send email with the following error:", then please have a look at the following section.

Where can I get my SMTP email server address, user and password?

Because each email account provider has different server address, so you should query your SMTP server address from your email account provider. To prevent spreading email from the server, most SMTP servers also require user authentication. User name is your email address or your email address without domain part, it depends on your email provider setting.

When you execute above example code, if you get error about "Networking connection" or "No such host", it is likely that your SMTP server address is not correct. If you get an error like "5xx Relay denied", it is likely that you did not set user authentication. Another common error is "5xx Must issue a STARTTLS command first" or "No supported authentication marshal found!", that is because your SMTP server requires user authentication under SSL connection. You can set the SSL connection to solve this problem.

Finally, if you have already set your account in your email client such as Outlook or Window Mail, you can query your SMTP server address, user in your email client. For example, you can choose menu -> "Tools" - > - "Accounts" - > "Your email account" - > "Properties" - > "Servers" in Outlook express or Windows Mail to get your SMTP server, user. Using EASendMail to send email does not require you have email client installed on your machine or MAPI, however you can query your exist email accounts in your email client.

c# console email sample

Email Address Syntax and Multiple Recipients

Mail Address Syntax in EASendMail SMTP Component:

For single email address (From, ReplyTo, ReturnPath), the syntax can be: ["][display name]["]<email address>.
For example: "Tester, T" <test@adminsystem.com>, Tester <test@adminsystem.com>, <test@adminsystem.com> or test@adminsystem.com.

For mulitple email address (To, CC, Bcc), the syntax can be: [single email],[single email]... (,;\r\n) can be used to separate multiple email addresses.
For example: "Tester, T" <test1@adminsystem.com>, Tester2 <test2@adminsystem.com>, <test3@adminsystem.com>, test4@adminsystem.com

To better understand the email address syntax in EASendMail, please refer to the following codes.

/*[C# Example - Email syntax]*/
//From is a MailAddress object, in C#/CSharp, it supports implicit converting from string.
// The syntax is like this: "test@adminsystem.com" or "Tester<test@adminsystem.com>"
// The example code without implicit converting.
oMail.From = new MailAddress( "Tester", "test@adminsystem.com" ); 
oMail.From = new MailAddress( "Tester<test@adminsystem.com>"); 
oMail.From = new MailAddress( "test@adminsystem.com" ); 

//To, Cc and Bcc is a AddressCollection object, in C#/CSharp, it supports implicit converting
// from string. Multiple addresses are separated with (,;) 
// The syntax is like this: "test@adminsystem.com, test1@adminsystem.com" 
// The example code without implicit converting 
oMail.To = new AddressCollection( "test1@adminsystem.com, test2@adminsystem.com" ); 
oMail.To = new AddressCollection( "Test1<test@adminsystem.com>, Test2<test2@adminsystem.com>");
// You can add more recipient by Add method 
oMail.To.Add( new MailAddress( "tester", "test@adminsystem.com"));

// You can also add  carbon copy (CC) or blind carbon copy (BCC) in the email.
oMail.Cc.Add( new MailAddress( "CC recipient", "cc@adminsystem.com"));
oMail.Bcc.Add( new MailAddress( "Bcc recipient", "bcc@adminsystem.com"));

Send email over SSL Connection

SSL connection encrypts data between the SMTP component and SMTP server to protects user, password and email content in TCP/IP level. Now this technology is commonly used and many SMTP servers are deployed with SSL such as Gmail. There are two ways to deploy SSL on SMTP server: 1. Using STARTTLS command to switch SSL channel on normal SMTP port (25); 2. Deploying SSL on another port (465 or other port, you may query it from your server administrator) directly. EASendMail SMTP component supports both ways.

The following samples demonstrate how to send email over SSL connection with Gmail, Yahoo and Hotmail account.

Send email by Gmail account with SSL connection

/*[C# Example - Send Email by Gmail Account with SSL connection]*/
using System;
using System.Collections.Generic;
using System.Text;
using EASendMail; //add EASendMail namespace

namespace mysendemail
{
    class Program
    {
        static void Main(string[] args)
        {
            SmtpMail oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();
        
            //Your gmail email address
            oMail.From = "gmailid@gmail.com";
            //Set recipient email address
            oMail.To = "support@emailarchitect.net";
            //Set email subject
            oMail.Subject = "test email from gmail account";
            //Set email body
            oMail.TextBody = "this is a test email sent from c# project with gmail.";

            //Gmail SMTP server address
            SmtpServer oServer = new SmtpServer("smtp.gmail.com");
            //gmail user authentication should use your 
            //gmail email address as the user name 
             oServer.User = "gmailid@gmail.com";
            oServer.Password = "yourpassword";

            //Send email over SSL/TLS connection.
            oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

            try
            {
                Console.WriteLine("start to send email over SSL ...");
                oSmtp.SendMail(oServer, oMail);
                Console.WriteLine("email was sent successfully!");
            }
            catch (Exception ep)
            {
                Console.WriteLine("failed to send email with the following error:");
                Console.WriteLine(ep.Message);
            }
        }
    }
}

Send email by Yahoo account with SSL connection

/*[C# Example - Send Email by Yahoo Account with SSL connection]*/
using System;
using System.Collections.Generic;
using System.Text;
using EASendMail; //add EASendMail namespace

namespace mysendemail
{
    class Program
    {
        static void Main(string[] args)
        {
            SmtpMail oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();
        
            //Your yahoo email address
            oMail.From = "myid@yahoo.com";
            //Set recipient email address
            oMail.To = "support@emailarchitect.net";
            //Set email subject
            oMail.Subject = "test email from yahoo account";
            //Set email body
            oMail.TextBody = "this is a test email sent from c# project with yahoo.";

            //Yahoo SMTP server address
            SmtpServer oServer = new SmtpServer("smtp.mail.yahoo.com");
            //yahoo user authentication should use your 
            //yahoo email address as the user name. 
            oServer.User = "myid@yahoo.com";
            oServer.Password = "yourpassword";

            //Because yahoo deploys SMTP server on 465 port with direct SSL connection.
            //So we should change the port to 465.
            oServer.Port = 465;
            
            //Send email over SSL/TLS connection.
            oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

            try
            {
                Console.WriteLine("start to send email over SSL ...");
                oSmtp.SendMail(oServer, oMail);
                Console.WriteLine("email was sent successfully!");
            }
            catch (Exception ep)
            {
                Console.WriteLine("failed to send email with the following error:");
                Console.WriteLine(ep.Message);
            }
        }
    }
}

Send email by MSN/hotmail account with SSL connection

/*[C# Example - Send Email by MSN/Hotmail Account with SSL connection]*/
using System;
using System.Collections.Generic;
using System.Text;
using EASendMail; //add EASendMail namespace

namespace mysendemail
{
    class Program
    {
        static void Main(string[] args)
        {
            SmtpMail oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();
        
            //Your hotmail email address
            oMail.From = "liveid@hotmail.com";
            //Set recipient email address
            oMail.To = "support@emailarchitect.net";
            //Set email subject
            oMail.Subject = "test email from hotmail account";
            //Set email body
            oMail.TextBody = "this is a test email sent from c# project with hotmail.";

            //Hotmail SMTP server address
            SmtpServer oServer = new SmtpServer("smtp.live.com");
            //hotmail user authentication should use your 
            //email address as the user name. 
            oServer.User = "liveid@hotmail.com";
            oServer.Password = "yourpassword";

            //Send email over SSL/TLS connection.
            oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

            try
            {
                Console.WriteLine("start to send email over SSL...");
                oSmtp.SendMail(oServer, oMail);
                Console.WriteLine("email was sent successfully!");
            }
            catch (Exception ep)
            {
                Console.WriteLine("failed to send email with the following error:");
                Console.WriteLine(ep.Message);
            }
        }
    }
}

Reply-To, Return-Path and Mail Priority

If you want to set another email address to get the replied email rather than your From address, you can use ReplyTo property.

If you want to set another email address to get the delivery report rather than your From address, you can use ReturnPath property.

If you want to set Higher or Lower priority to your email, you can use Priority prority

Send email directly without SMTP server(MX DNS lookup)

In general, we send email via specified SMTP server. How does the specified SMTP server know what address this email should be sent to? The answer is... it queries MX record of recipient's domain via DNS lookup. It then forwards this email to the SMTP server queried from DNS server. If recipient's server doesn't work fine, sender's SMTP server will send a failure-delivery report to the sender telling it failed to send out the email.

How does EASendMail SMTP component work with "Send email directly"? Firstly, it queries MX record for recipient address from DNS, then sends email to recipient's email server directly. In short, if no SMTP server is specified in the code, EASendMail will send email to recipient directly. Since querying DNS server consumes CPU time and networking resource, the performance of "Send email directly" is lower than sending email with specified SMTP server. Moreover, nowadays more and more SMTP servers block email sent from dynamic IP address, so we don't recommend you to use "Direct Send Email" except you have a static IP address or you encounter problem with your ISP SMTP server.

Every recipient may have different SMTP server, if there are multiple recipients in one message and you want to send email directly, you should send the email to the recipients one by one.

To implement this feature, you just need to put nothing to SMTP server address.

/*[C# Example - Send Email Directly without SMTP server]*/
using System;
using System.Collections.Generic;
using System.Text;
using EASendMail; //add EASendMail namespace

namespace mysendemail
{
    class Program
    {
        static void Main(string[] args)
        {
            SmtpMail oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();
        
            //Set sender email address, please change it to yours
            oMail.From = "test@emailarchitect.net";
            //Set recipient email address, please change it to yours
            oMail.To = "support@emailarchitect.net";
            //Set email subject
            oMail.Subject = "direct email sent from c# project";
            //Set email body
            oMail.TextBody = "this is a test email sent from c# project directly";

            //Set SMTP server address to ""
            SmtpServer oServer = new SmtpServer("");
            
            //Do not set user authentication
            //Do not set SSL connection
           
            try
            {
                Console.WriteLine("start to send email directly ...");
                oSmtp.SendMail(oServer, oMail);
                Console.WriteLine("email was sent successfully!");
            }
            catch (Exception ep)
            {
                Console.WriteLine("failed to send email with the following error:");
                Console.WriteLine(ep.Message);
            }
        }
    }
}

With above code, if you get error like "5xx IP address rejected", that means your IP address is blocked by the recipient's SMTP server. You have to specify a SMTP server with user authentication to relay your email.

Send email with Html body

If you want to specify the font, color or insert pictures in your email, you should use Html email format instead of Plain text email format. The following sample demonstrates how to use HtmlBody to send a HTML email.

/*[C# Example - Send HTML email]*/
using System;
using System.Collections.Generic;
using System.Text;
using EASendMail; //add EASendMail namespace

namespace mysendemail
{
    class Program
    {
        static void Main(string[] args)
        {
            SmtpMail oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();
        
            //Set sender email address, please change it to yours
            oMail.From = "test@emailarchitect.net";
            //Set recipient email address, please change it to yours
            oMail.To = "support@emailarchitect.net";
            //Set email subject
            oMail.Subject = "test html email from C#";
            //Set Html email body
            oMail.HtmlBody = "<font size=5>This is</font> <font color=red><b>a test</b></font>";

            //Your smtp server address
            SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");
            //User and password for ESMTP authentication, if your server doesn't require
            //User authentication, please remove the following codes.            
            oServer.User = "test@emailarchitect.net";
            oServer.Password = "testpassword";

            //If your smtp server requires SSL connection, please add this line
            //oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

            try
            {
                Console.WriteLine("start to send HTML email ...");
                oSmtp.SendMail(oServer, oMail);
                Console.WriteLine("email was sent successfully!");
            }
            catch (Exception ep)
            {
                Console.WriteLine("failed to send email with the following error:");
                Console.WriteLine(ep.Message);
            }
        }
    }
}

After you received the email by your email client, the body text is like this:

c# html email sample

Of course, you don't have to write the HTML source body text in your application manually. You can build a html file with HTML tools and use ImportHtmlBody method to import the html file directly.

You can also refer to the htmlmail.xx samples in EASendMail SMTP Component installer. Those samples demonstrate how to build a HTML email editor and send HTML email with attachment or embedded pictures/images.

c# html editor

Send email with Attachment

To send an email with attachment, we need to use AddAttachment method. This method can attach a file to the email message from local disk or a remote URL.

/*[C# Example - Send Email with Attachment]*/
using System;
using System.Collections.Generic;
using System.Text;
using EASendMail; //add EASendMail namespace

namespace mysendemail
{
    class Program
    {
        static void Main(string[] args)
        {
            SmtpMail oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();
        
            //Set sender email address, please change it to yours
            oMail.From = "test@emailarchitect.net";
            //Set recipient email address, please change it to yours
            oMail.To = "support@emailarchitect.net";
            //Set email subject
            oMail.Subject = "test html email with attachment";
            //Set Html email body
            oMail.HtmlBody = "<font size=5>This is</font> <font color=red><b>a test</b></font>";

            //Your smtp server address
            SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");
            //User and password for ESMTP authentication, if your server doesn't require
            //User authentication, please remove the following codes.            
            oServer.User = "test@emailarchitect.net";
            oServer.Password = "testpassword";

            //If your smtp server requires SSL connection, please add this line
            //oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

            try
            {
                //adds attachment from local disk
                oMail.AddAttachment( "d:\\test.pdf" );
                
                //adds attachment from remote website
                oMail.AddAttachment( "http://www.emailarchitect.net/webapp/img/logo.jpg" );

                Console.WriteLine("start to send email with attachment ...");
                oSmtp.SendMail(oServer, oMail);
                Console.WriteLine("email was sent successfully!");
            }
            catch (Exception ep)
            {
                Console.WriteLine("failed to send email with the following error:");
                Console.WriteLine(ep.Message);
            }
        }
    }
}

Send email with Embedded Picture/Image

To attach an embedded picture to email, you should add an attachment to email at first. Then you should assign an unique identifier(contentid) to this attachment. Finally, you need to replace the <img src="your file name" /> to <img src="cid:yourcontentid" />.

/*[C# Example - Send Email with Embedded Picture/Image]*/
using System;
using System.Collections.Generic;
using System.Text;
using EASendMail; //add EASendMail namespace

namespace mysendemail
{
    class Program
    {
        static void Main(string[] args)
        {
            SmtpMail oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();
        
            //Set sender email address, please change it to yours
            oMail.From = "test@emailarchitect.net";
            //Set recipient email address, please change it to yours
            oMail.To = "support@emailarchitect.net";
            //Set email subject
            oMail.Subject = "test html email with attachment";

            //Your smtp server address
            SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");
            //User and password for ESMTP authentication, if your server doesn't require
            //User authentication, please remove the following codes.            
            oServer.User = "test@emailarchitect.net";
            oServer.Password = "testpassword";

            //If your smtp server requires SSL connection, please add this line
            //oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

            try
            {
                //adds attachment from local disk
                Attachment oAttachment = oMail.AddAttachment( "d:\\test.gif" );

                //specifies the attachment as an embedded picture
                //contentid can be any string.
                string contentID = "test001@host";
                oAttachment.ContentID = contentID;
                oMail.HtmlBody = "<html><body>this is a <img src=\"cid:"
                     + contentID + "\"> embedded picture.</body></html>";

                Console.WriteLine("start to send email with embedded image...");
                oSmtp.SendMail(oServer, oMail);
                Console.WriteLine("email was sent successfully!");
            }
            catch (Exception ep)
            {
                Console.WriteLine("failed to send email with the following error:");
                Console.WriteLine(ep.Message);
            }
        }
    }
}

To attach embedded images/pictures, SmtpMail.ImportHtmlBody and SmtpMail.ImportHtml methods are strongly recommended. With these methods, you don't have to specify the ContentID manually. The html source/file html body can be imported to email with embedded pictures automatically.

Send email with Digital Signature(S/MIME)

Digital signature prevents email content is faked or changed in transport level. Encrypting email protects email content from exposure to inappropriate recipients. Both digital signature and email encrypting depend on digital certificate.

If you have an email digital signature certificate installed on your machine, you can find it in "Control Panel" -> "Internet Options" -> "Content" -> "Certificates" -> "Personal".

c# email ceritificate

Then you can use your email certificate to sign the email by the following code. If you don't have a certificate for your email address, you MUST get a digital certificate for personal email protection from third-party certificate authorities such as www.verisign.com.

/*[C# Example - Send Email with Digital Signature(S/MIME)]*/
using System;
using System.Collections.Generic;
using System.Text;
using EASendMail; //add EASendMail namespace

namespace mysendemail
{
    class Program
    {
        static void Main(string[] args)
        {
            SmtpMail oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();
        
            //Set sender email address, please change it to yours
            oMail.From = "test@emailarchitect.net";
            //Set recipient email address, please change it to yours
            oMail.To = "support@emailarchitect.net";
            //Set email subject
            oMail.Subject = "test email with digital signature";
            //Set email body
            oMail.TextBody = "this is a test email with digital signature";

            //Your smtp server address
            SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");
            //User and password for ESMTP authentication, if your server doesn't require
            //User authentication, please remove the following codes.            
            oServer.User = "test@emailarchitect.net";
            oServer.Password = "testpassword";

            try
            {
                //Find certificate by email adddress in My Personal Store.
                //Once the certificate is loaded to From, the email content
                //will be signed automatically                 
                oMail.From.Certificate.FindSubject(oMail.From.Address,
                    Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER,
                    "My");
            }
            catch (Exception exp)
            {
                Console.WriteLine("No sign certificate found for <" + 
                    oMail.From.Address + ">:" + exp.Message);
            }
            
            //If your smtp server requires SSL connection, please add this line
            //oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

            try
            {
                Console.WriteLine("start to send email with digital signature ...");
                oSmtp.SendMail(oServer, oMail);
                Console.WriteLine("email was sent successfully!");
            }
            catch (Exception ep)
            {
                Console.WriteLine("failed to send email with the following error:");
                Console.WriteLine(ep.Message);
            }
        }
    }
}

Send email with Email Encryption(S/MIME)

After the recipient received your email with digital signature, the recipient can get your digital certificate public key from your digital signature. Then the recipient can encrypt an email with your public key and send it to you. Only you can decrypt this email with your private key. That is how S/MIME can protect your email content. If you don't expose your digital certificate private key to others, none can read your email which is encrypted by your public key.

If you received an email with digital signature, your email client usually stores the public key of the sender in "Control Panel" -> "Internet Options" -> "Content" -> "Certificates" -> "Other People".

Then you can use the following code to encrypt email and send it to your recipient.

/*[C# Example - Send Email with Digital Signature(S/MIME)]*/
using System;
using System.Collections.Generic;
using System.Text;
using EASendMail; //add EASendMail namespace

namespace mysendemail
{
    class Program
    {
        static void Main(string[] args)
        {
            SmtpMail oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();
        
            //Set sender email address, please change it to yours
            oMail.From = "test@emailarchitect.net";
            //Set recipient email address, please change it to yours
            oMail.To = "support@emailarchitect.net";
            //Set email subject
            oMail.Subject = "test encrypted email";
            //Set email body
            oMail.TextBody = "this is a test email with email encryption";

            //Your smtp server address
            SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");
            //User and password for ESMTP authentication, if your server doesn't require
            //User authentication, please remove the following codes.            
            oServer.User = "test@emailarchitect.net";
            oServer.Password = "testpassword";

            try
            {
                //Find certificate by email adddress in My Personal Store.
                //Once the certificate is loaded to From, the email content
                //will be signed automatically 

                oMail.From.Certificate.FindSubject(oMail.From.Address,
                    Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER,
                    "My");
            }
            catch (Exception exp)
            {
                Console.WriteLine("No sign certificate found for <" + 
                    oMail.From.Address + ">:" + exp.Message);
            }
         
 
            int count = oMail.To.Count;
            for (int i = 0; i < count; i++)
            {
                MailAddress oAddress = oMail.To[i] as MailAddress;
                try
                {
                    //Find certificate by email adddress in My Other Peoples Store.
                    //The certificate can be also imported by *.cer file like this: 
                    //oAddress.Certificate.Load("c:\\encrypt1.cer");
                    //Once the certificate is loaded to MailAddress, the email content
                    // will be encrypted automatically

                    oAddress.Certificate.FindSubject(oAddress.Address,
                        Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER,
                        "AddressBook");
                }
                catch (Exception ep)
                {
                    try
                    {
                        oAddress.Certificate.FindSubject(oAddress.Address,
                            Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER,
                            "My");
                    }
                    catch (Exception exp)
                    {
                        Console.WriteLine("No encryption certificate found for <" +
                             oAddress.Address + ">:" + exp.Message);
                    }
                }
            }           
            
            //If your smtp server requires SSL connection, please add this line
            //oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

            try
            {
                Console.WriteLine("start to send encrypted email ...");
                oSmtp.SendMail(oServer, oMail);
                Console.WriteLine("email was sent successfully!");
            }
            catch (Exception ep)
            {
                Console.WriteLine("failed to send email with the following error:");
                Console.WriteLine(ep.Message);
            }
        }
    }
}

If you received digital signed and encrypted email by Windows Mail(Outlook Express), it looks like this:

c# sign and encrypt email

Send email with Event Handler

After SendMail method is invoked, if you want to know the progress of the email sending, you should use Event Handler. The following sample codes demonstrate how to use Event Handler to monitor the progress of email sending.

/*[C# Example - Send Email with Event Handler]*/
using System;
using System.Collections.Generic;
using System.Text;
using EASendMail; //add EASendMail namespace

namespace mysendemail
{
    class Program
    {
       public static void OnSecuring(
            object sender,
            ref bool cancel
        )
        {
            Console.WriteLine("Securing ... ");
        }

        public static void OnAuthorized(
            object sender,
            ref bool cancel
        )
        {
            Console.WriteLine("Authorized");
        }

        public static void OnIdle(
            object sender,
            ref bool cancel
        )
        {
            //this event is fired when the SmtpClient is wait for response from
            // smtp server, if you add Application.DoEvents in windows form application,
            // it can prevent your form has no response before SendMail is not returned.
            //Application.DoEvents();
        }

        public static void OnConnected(
            object sender,
            ref bool cancel
        )
        {
            Console.Write("Connected\r\n");
        }

        public static void OnSendingDataStream(
            object sender,
            int sent,
            int total,
            ref bool cancel
        )
        {
            Console.WriteLine(String.Format("{0}/{1} sent", sent, total));
        }    
        
        static void Main(string[] args)
        {
            SmtpMail oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();
        
            //Set sender email address, please change it to yours
            oMail.From = "test@emailarchitect.net";
            //Set recipient email address, please change it to yours
            oMail.To = "support@emailarchitect.net";
            //Set email subject
            oMail.Subject = "test email from c# with event handler";
            //Set email body
            oMail.TextBody = "this is a test email sent from c# project with event handler";

            //Your smtp server address
            SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");
            //User and password for ESMTP authentication, if your server doesn't require
            //User authentication, please remove the following codes.            
            oServer.User = "test@emailarchitect.net";
            oServer.Password = "testpassword";

            //If your smtp server requires SSL connection, please add this line
            //oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

            //add event handlers to current SmtpClient instance.
            oSmtp.OnAuthorized += new SmtpClient.OnAuthorizedEventHandler( OnAuthorized );
            oSmtp.OnIdle += new SmtpClient.OnIdleEventHandler( OnIdle );
            oSmtp.OnConnected += new SmtpClient.OnConnectedEventHandler( OnConnected );
            oSmtp.OnSecuring += new SmtpClient.OnSecuringEventHandler( OnSecuring );
            oSmtp.OnSendingDataStream += 
                new SmtpClient.OnSendingDataStreamEventHandler( OnSendingDataStream );

            try
            {
                Console.WriteLine("start to send email ...");
                oSmtp.SendMail(oServer, oMail);
                Console.WriteLine("email was sent successfully!");
            }
            catch (Exception ep)
            {
                Console.WriteLine("failed to send email with the following error:");
                Console.WriteLine(ep.Message);
            }
        }
    }
}

Send email with Asynchronous Mode

In synchronous mode, once SendMail method is called, it returns to application after the method is complete. Therefore, if the runtime (it depends on the networking connection and the email size) is long, your application cannot do anything before this method ends, which results "my application is blocked or halted". In contrast, in asynchronous mode, as BeginSendMail method works in background, this methods return to application immediately no matter the running method is complete or not.

The following sample codes demonstrate how to send email in asynchronous mode.

/*[C# Example - Send Email with Asynchronous Mode]*/
using System;
using System.Collections.Generic;
using System.Text;
using EASendMail; //add EASendMail namespace

namespace mysendemail
{
    class Program
    {
        static void Main(string[] args)
        {
            SmtpMail oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();
        
            //Set sender email address, please change it to yours
            oMail.From = "test@emailarchitect.net";
            //Set recipient email address, please change it to yours
            oMail.To = "support@emailarchitect.net";
            //Set email subject
            oMail.Subject = "test email from c# with asynchronous mode";
            //Set email body
            oMail.TextBody = "this is a test email sent from c# project with asynchronous mode";

            //Your smtp server address
            SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");
            //User and password for ESMTP authentication, if your server doesn't require
            //User authentication, please remove the following codes.            
            oServer.User = "test@emailarchitect.net";
            oServer.Password = "testpassword";

            //If your smtp server requires SSL connection, please add this line
            //oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

            try
            {
                Console.WriteLine("start to send email in asynchronous mode...");
                SmtpClientAsyncResult oResult = oSmtp.BeginSendMail(
                        oServer, oMail, null, null);

                //Wati for the email sending...
                while (!oResult.IsCompleted)
                {
                    Console.WriteLine("waiting..., you can do other thing!");
                    oResult.AsyncWaitHandle.WaitOne(50, false);
                }

                oSmtp.EndSendMail(oResult);
                Console.WriteLine("email was sent successfully!");
            }
            catch (Exception ep)
            {
                Console.WriteLine("failed to send email with the following error:");
                Console.WriteLine(ep.Message);
            }
        }
    }
}

Send email with Multiple Threads(Mass Mail)

Based on asynchronous mode, you can create multiple SmtpClient instances in your application and send email in multiple threads. Here is a simple sample demonstrates how to use asynchronous mode to send email in multiple threads.

/*[C# Example - Send Mass Emails with  Multiple Threads(Mass Mail)]*/
using System;
using System.Collections.Generic;
using System.Text;
using EASendMail; //add EASendMail namespace

namespace mysendemail
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] arRcpt = new string[]{"test1@adminsystem.com", 
                "test2@adminsystem.com",
                "test3@adminsystem.com" };

            int nRcpt = arRcpt.Length;
            SmtpMail[] arMail = new SmtpMail[nRcpt];
            SmtpClient[] arSmtp = new SmtpClient[nRcpt];
            SmtpClientAsyncResult[] arResult = new SmtpClientAsyncResult[nRcpt];
            for (int i = 0; i < nRcpt; i++)
            {
                arMail[i] = new SmtpMail("TryIt");
                arSmtp[i] = new SmtpClient();
            }

            for (int i = 0; i < nRcpt; i++)
            {
                SmtpMail oMail = arMail[i];
                //Set sender email address
                oMail.From = "sender@emailarchitect.net";
                //Set recipient email address
                oMail.To = arRcpt[i];
                //Set email subject
                oMail.Subject = "mass email test from c#";
                //Set email body
                oMail.TextBody = "test from c#, this email is sent to " + arRcpt[i];

                //Your smtp server address
                SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");
                //User and password for ESMTP authentication, if your server doesn't require
                //User authentication, please remove the following codes.            
                oServer.User = "test@emailarchitect.net";
                oServer.Password = "testpassword";

                //If your smtp server requires SSL connection, please add this line
                //oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                SmtpClient oSmtp = arSmtp[i];
                //Submit email to BeginSendMail method and return
                //to process another email
                arResult[i] = oSmtp.BeginSendMail(oServer, oMail, null, null );   
                Console.WriteLine( String.Format( "Start to send email to {0} ...",
                    arRcpt[i] ));
            }

            //all emails were sent by BeginSendMail Method
            //now get result by EndSendMail method
            int nSent = 0;
            while (nSent < nRcpt)
            {
                for (int i = 0; i < nRcpt; i++)
                {
                    //this email has sent
                    if (arResult[i] == null)
                        continue;

                    //wait for specified email ...
                    if (!arResult[i].AsyncWaitHandle.WaitOne(10, false))
                    {
                        continue;
                    }

                    try
                    {
                        //this email is finished, using EndSendMail to get result
                        arSmtp[i].EndSendMail(arResult[i]);
                        Console.WriteLine(String.Format("Send email to {0} successfully",
                            arRcpt[i]));
                    }
                    catch (Exception ep)
                    {
                        Console.WriteLine(
                           String.Format("Failed to send email to {0} with error {1}: ",
                           arRcpt[i], ep.Message));
                    }
                    //Set this email result to null, then it won't be processed again
                    arResult[i] = null;
                    nSent++;
                }
            }
        }
    }
}

Total Sample Projects

After you downloaded the EASendMail SMTP Component Installer and install it on your machine, there are many samples in the installation path.

asp Send email from ASP (VBScript, JScript) - ActiveX/COM
asp_queue Send email from ASP to EASendMail Service. (VBScript, JScript) - ActiveX/COM
asp_queue_database Send email from ASP to EASendMail Service, EASendMail service will select recipients from database. (VBScript, JScript) - ActiveX/COM
asp_net Send email from ASP.NET. (C#, VB, JScript.NET)
asp_net_batch Send bulk emails with multiple threads from ASP.NET. (C#, VB)
asp_net_queue Send email from ASP.NET to EASendMail Service. (C#, VB, JScript.NET)
asp_net_queue_database Send email from ASP.NET to EASendMail Service, EASendMail service will select recipients from database. (C#, VB, JScript.NET)
simple.vb6 Send text/plain email from Visual Basic 6.0. This sample also demonstrates digital signature, email encryption. (VB6) - ActiveX/COM
simple.vcNative Send text/plain email from Visual C++. This sample also demonstrates digital signature, email encryption. (Visual C++) - ActiveX/COM
simple.vb Send text/plain email from Visual Basic.NET. This sample also demonstrates digital signature, email encryption.
simple.csharp Send text/plain email from C#. This sample also demonstrates digital signature, email encryption.
simple.vc Send text/plain email from managed c++. This sample also demonstrates digital signature, email encryption.
htmlmail.vb6 Send text/html email from Visual Basic 6.0. This sample also demonstrates embedded pictures, digital signature, email encryption. (VB6) - ActiveX/COM
htmlmail.vcNative Send text/html email from Visual C++. This sample also demonstrates embedded pictures, digital signature, email encryption. (Visual C++) - ActiveX/COM
htmlmail.vb Send text/html email from Visual Basic.NET. This sample also demonstrates embedded pictures, digital signature, email encryption.
htmlmail.csharp Send text/html email from C#. This sample also demonstrates embedded pictures, digital signature, email encryption.
mass.vb6 Send email by FastSender with multiple threadings. This sample also demonstrates email address validating. (VB6) - ActiveX/COM
mass.vb Send email by BeginSendMail with multiple threadings. This sample also demonstrates email address validating.
mass.csharp Send email by BeginSendMail with multiple threadings. This sample also demonstrates email address testing.
samples_vs2008\pocketpc.mobile.cs Send email from PocketPC/Windows Mobile System.
samples_vs2008\pocketpc.mobile.vb Send email from PocketPC/Windows Mobile System.

See Also

Send Email in Visual Basic.NET - Toturial
Send Email in Managed C++ - Toturial
Send Email in Visual Basic 6.0 - Toturial
Send Email in Visual C++ - Toturial

Free Email Support

Not enough? Please contact our technical support team.

Support@EmailArchitect.NET
VIP@EmailArchitect.NET(Registered User)

Remarks
We usually reply emails in 24hours. The reason for getting no response is likely that your smtp server bounced our reply. In this case, please try to use another email address to contact us. Your Hotmail or Yahoo email account is recommended.



2001-2011 © Copyright AdminSystem Software Limited. All rights reserved.   About us  Site Map                       Follow emailarchitect on Twitter