EASendMail SMTP Component > Developer Center > C# - .NET Framework > Send Email in C# using SMTP/SSL/Queue/Embedded Image/S/MIME/EWS/WebDAV - Tutorial

Send Email in C# using SMTP/SSL/Queue/Embedded Image/S/MIME/EWS/WebDAV - Tutorial

Date: June 26, 2014

Introduction

This tutorial introduces how to send email in C# using SMTP. It also demonstrates SSL, S/MIME, Embedded Images, Email Queue, Multiple Threads, EWS and WebDAV usage.

This tutorial is for C# .NET framework application. If you want to send email in Windows Store Apps (Window RT/Metro Style App), please go to Send Email in C# from Windows Store Apps - XAML - Tutorial

Tutorial Index

Send Email in A Simple C# Project using SMTP protocol

Installation

EASendMail is a SMTP component which supports all operations of SMTP/ESMTP protocols (RFC 821, RFC 822, RFC 2554). It also supports Exchange Web Service (EWS) and WebDAV protocols. Before you can use the following example codes, you should download the EASendMail Installer and install it on your machine at first.

Send email in a simple C# project

To better demonstrate how to send email in C# using SMTP protocol, let's create a C# console project named "mysendmail" at first, and then add the reference of EASendMail in your project.

send email in c# console project

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.

add reference in c#

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, 4.5 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.
EASendMaill45.dll Built with .NET Framework 4.5
It requires .NET Framework 4.5 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.

[C# - Send Email using SMTP - Example]

Now add the following codes to the project and change From, To, Server, User and Password to corresponding value. The following example codes demonstrate how to send email using SMTP protocol in C# project.

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 TLS connection, please add this line
            // oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

            // If your smtp server requires implicit SSL connection on 465 port, please add this line
            // oServer.Port = 465;
            // 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.

Common SMTP Transport Error

When you execute above example code, if it threw an exception about "Networking connection" or "No such host", it is likely that your SMTP server address is not correct. If it threw an exception about "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. You can learn more detail in Troubleshooting 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.

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

The following example codes demonstrates how to specify display name and email address by different syntax.

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>
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

[C# - Email Address Syntax - Example]

To better understand the email address syntax, please refer to the following codes. It demonstrate how to specify from, to, cc by different email address syntax.

// From is a MailAddress object, 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, 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"));

From, ReplyTo, Sender and Return-Path

From, Reply-To, Sender and Return-Path are common email headers in email message. You should always set From property at first, it is a MUST to identify the email sender. The following table lists the header and corresponding properties:

Header Property
From SmtpMail.From
Reply-To SmtpMail.ReplyTo
Sender SmtpMail.Sender
Return-Path SmtpMail.ReturnPath
  • From

    This property indicates the original email sender. This is what you see as the "FROM" in most mail clients.

  • Reply-To

    This property indicates the reply address. Basically, when the user clicks "reply" in mail client, the Reply-To value should be used as the recpient address of the replied email. If you don't set this property, the Reply address is same as From address.

  • Sender

    This property indicates the who submit/send the email. When the user received the email, the email client displays: From: "sender address" on behalf of "from address". If you don't set this property, the Sender address is same as From address. Sender property is common used by mail listing provider. This property also takes effect to DKIM/DomainKeys signature, if Sender is different with From address, then you should sign DKIM/DomainKeys based on Sender domain instead of From address domain.

  • Return-Path

    This property indicates the delivery notification report address. If you don't set this property, the Return-Path address is same as From address. This property also takes effect to SPF record, if Return-Path is different with From address, then remote SMTP server checkes SPF record of Return-Path instead of From address.

[C# - From, ReplyTo, Sender and Return-Path in Email - Example]

The following example codes demonstrate how to specify From, Reply-To, Sender and Return-Path in Email. With the following example codes:

  • If the email couldn't be delivered to recipient, a non-delivery report will be sent to "report@emailarchitect.net".
  • If the user received the email, the email client will display: "sender@emailarchitect.net" on behalf of "from@adminsystem.com".
  • If the user click "reply", the replied email will be sent to "reply@adminsystem.com".
SmtpMail oMail = new SmtpMail("TryIt");
oMail.From = "from@adminsystem.com";
oMail.ReplyTo = "reply@adminsystem.com";
oMail.Sender = "sender@emailarchitect.net";
oMail.ReturnPath = "report@emailarchitect.net";

Mail Priority

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

[C# - Mail Priority - Example]

// Set high priority
oMail.Priority = MailPriority.High;

Troubleshooting

When you send email in above simple C# project, if it threw an exception, please have a look at the following tips:

"No Such Host" exception

This error means DNS server cannot resolve SMTP server, you should check if you input correct server address. If your server address is correct, you should check if your DNS server setting is correct.

Common "Networking Connection" Exception

This error means there is a problem with networking connection to SMTP server. You can use Windows built-in Telnet command to detect the networking connection.

Using Telnet to detect networking connection to SMTP server

Notice: in Windows 2008/Windows 8 or later version, "Telnet Client" is not installed by default, you should enable this command in "Control Panel" -> "Programs and Features" -> "Turn Windows feature on or off" -> have "Telnet Client" checked.

Under DOS command prompt, input "telnet [serveraddress] [port]":

telnet mail.emailarchitect.net 25
press enter.

If the networking connection to your SMTP server is good, it should return a message like "220 ...". If it returns "Could not open connection to ...", that means the networking connection to SMTP server is bad, or outbound 25 port is blocked by anti-virus software, firewall or ISP. Please have a look at the following screenshot:

detect SMTP connection using telnet

SMTP 25, 587, 465 port

25 port is the default SMTP server port to receive email. However, some ISP block outbound 25 port to prevent user to send email directly to other SMTP server. Therefore, many email providers also provide an alternative port 587 to receive email from such users. 465 port is the common port used to receive email over implicit SSL connection. If you use telnet to test 465 port, it doesn't return the "220...", because it requires SSL hand shake. But if the connection is ok, telnet returns a flash cursor.

"5xx ... IP address block or on black list or bad reputation" Exception

This error means SMTP server blocks your IP address or email content. You can try to set user/password in your codes to do user authentication and try it again. If email client set user authentication, most SMTP servers do not check client source IP address in black list.

"5xx user authenticaton" Exception

TThis error means user authentication is failed, you should check whether you input correct user/password. Password is always case-sensitive.

"5xx relay denied" Exception

For anti-spam policy, most SMTP servers do not accept the email to outbound domain without user authentication. You should set user/password in the codes and try it again.

"5xx Must issue a STARTTLS command first"

This error means SMTP server requires SSL/TLS connection. You should enable SSL/TLS connection like this:

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

"No supported authentication marshal found!"

This error means SMTP server doesn't support user authentication or it requires user authentication over SSL/TLS connection. You can try to remove user/password in your codes and try it again.

Other error returned by SMTP server

If SMTP server returns an error, it usually returns description about this error. Some descriptions also include a HTTP link, you can go to this linked web page to learn more detail. You can also use the following codes to generate a log file to learn all SMTP session between client and server.

[C# - Using log file to detect SMTP server response - Example]

try
{
    // add this line here to generate log file
    oSmtp.LogFileName = "d:\\smtp.txt"; 
    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);
}

Process Bounced Email (Non-Delivery Report)

If you sent email successfully without error, that means the email has been submitted to the SMTP server. The SMTP server will deliver the email in background, if the email couldn't be delivered, a Failure Report (NDS) will be sent back to your sender email address.

To retrieve and parse Failure Report (NDS), you should monitor your sender mailbox. I recommend that you use EAGetMail to monitor your sender mailbox using POP3/IMAP4/Exchange WebDAV/Exchange Web Service protocol. After you installed EAGetMail on your machine, there are several full samples named "parse_report.*" for VB.NET, C# in the installation path.

Email Tracking

Email tracking is used to verify that emails are actually read by recipients. There are two common solutions: Read Receipt and Linked Image Tracking

To learn more detail about Process Bounced Email (Non-Delivery Report) and Email Tracking, please have a look at this topic: Process Bounced Email (Non-Delivery Report) and Email Tracking

Bulk Email Sender Guidelines

If you are a mail listing provider and send bulk emails every day, of course you don't want your emails are blocked or moved to Junk folder of the recipient mailbox.

To increase the inbox delivery rate of your messages, make sure that all recipients on your distribution lists actually want to receive the mail. Have a look the topic for some tips on how to make sure your messages are welcomed by most email providers:
Bulk Email Sender Guidelines

Next Section

In this section, I introduced how to send email in a simple C# project using SMTP protocol. At next section I will introduce how to send email over SSL/TLS connection.

Next: Send email over SSL/TLS in C# >

In previous section, I introduced how to send email in a simple C# project. In this section, I will introduce how to send email over SSL/TLS connection in C#.

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, Yahoo and Hotmail. There are two ways to deploy SSL on SMTP server:

  • Explicit SSL (TLS) Using STARTTLS command to switch SSL channel on normal SMTP port (25 or 587);
  • Implicit SSL 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 connection can be specified by EASendMail.SmtpConnectType enumeration. Please see the following example code.

[C# - Send Email over SSL/TLS Setting - Example]

The following example codes demonstrates how to set SSL/TLS connection.

// Send email by normal TCP/IP without SSL connection
SmtpServer oServer = new SmtpServer("localhost 25");
oServer.ConnectType = SmtpConnectType.ConnectNormal;

// Send email by SSL connection with STARTTLS command switching
SmtpServer oServer = new SmtpServer("localhost 25");
oServer.ConnectType = SmtpConnectType.ConnectSTARTTLS;

// Send email by SSL connection with direct SSL.
SmtpServer oServer = new SmtpServer("localhost 465");
oServer.ConnectType = SmtpConnectType.ConnectDirectSSL;

// Send email by SSL connection with auto-detect.
// If port is 25 or 587, STARTTLS SSL will be used; otherwise direct SSL will be used.

SmtpServer oServer = new SmtpServer("localhost 465");
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto; 

SmtpServer oServer = new SmtpServer("localhost 25");
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

Remarks: All of samples in this section are based on first section: Send email in a simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.

[C# - Send Email over Implicit SSL on 465 port - Example]

The following example codes demonstrate how to send email over SSL connection on 465 port. To get full sample projects, please refer to Samples section.

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();
        
            oMail.From = "test@emailarchitect.net";
            oMail.To = "support@emailarchitect.net";
            oMail.Subject = "test email from c# project";
            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");
            
            // Set SSL 465 port
            oServer.Port = 465;

            // Set direct SSL connection
            oServer.ConnectType = SmtpConnectType.ConnectDirectSSL;

            // User and password for ESMTP authentication            
            oServer.User = "test@emailarchitect.net";
            oServer.Password = "testpassword";
 
            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);
            }
        }
    }
}

[C# - Send Email over TLS (Explicit SSL) on 25 or 587 port - Example]

The following example codes demonstrate how to send email over TLS (STARTTLS command, Explicit SSL) connection on 25 port. To get full samples projects, please refer to Samples section.

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();
        
            oMail.From = "test@emailarchitect.net";
            oMail.To = "support@emailarchitect.net";
            oMail.Subject = "test email from c# project";
            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");
            
            // Set 25 port, if your server uses 587 port, please change 25 to 587
            oServer.Port = 25;

            // Set TLS connection
            oServer.ConnectType = SmtpConnectType.ConnectSTARTTLS;

            // User and password for ESMTP authentication            
            oServer.User = "test@emailarchitect.net";
            oServer.Password = "testpassword";
 
            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);
            }
        }
    }
}

SMTP Server SSL Certificate

To send email over SSL/TLS connection, you don't need to install a certificate on your machine. The data is encrypted by server certificate public/private key pair.

SMTP Setting for Gmail, Yahoo, Hotmail and Office 365

Because most popluar email providers support or require SSL/TLS connection, so I will introduce specific setting for Gmail, Yahoo, Hotmail and Office 365 in the coming sections.

Next Section

At next section I will introduce how to send email using Gmail account in C#.

< Prev: Send email in a simple C# project | Next : Send email using Gmail in C# >

In previous section, I introduced how to send email over SSL/TLS connection. In this section, I will introduce how to send email using Gmail account in C#.

Gmail SMTP server address is "smtp.gmail.com". It requires implicit SSL or explicit SSL (TLS) connection, and you should use your Gmail email address as the user name for ESMTP authentication. For example: your email is "gmailid@gmail.com", and then the user name should be "gmailid@gmail.com".

Remarks: All of samples in this section are based on first section: Send email in a simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.

[C# - Send Email using Gmail Account over Implicit SSL on 465 Port]

The following example codes demonstrate how to send email using Gmail account over SSL in C#. To get full sample projects, please refer to Samples section.

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");
            
            // Set 465 port
            oServer.Port = 465;

            // detect SSL/TLS automatically
            oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

            // Gmail user authentication
            // For example: your email is "gmailid@gmail.com", then the user should be the same
            oServer.User = "gmailid@gmail.com";
            oServer.Password = "yourpassword";

            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);
            }
        }
    }
}
 

[C# - Send Email using Gmail Account over Explicit SSL (TLS) on 25 or 587 Port]

The following example codes demonstrate how to send email using Gmail account over TLS in C#. To get full sample projects, please refer to Samples section.

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");
            
            // Set 25 port, if you want to use 587 port, please change 25 5o 587
            oServer.Port = 25;

            // detect SSL/TLS automatically
            oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

            // Gmail user authentication
            // For example: your email is "gmailid@gmail.com", then the user should be the same
            oServer.User = "gmailid@gmail.com";
            oServer.Password = "yourpassword";

            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);
            }
        }
    }
}
 
Next Section

At next section I will introduce how to send email using Yahoo account in C#.

< Prev: Send email over SSL/TLS in C# | Next: Send email using Yahoo in C# >

In previous section, I introduced how to send email using Gmail account. In this section, I will introduce how to send email using Yahoo account in C#.

Yahoo SMTP server address is "smtp.mail.yahoo.com". It supports both Normal/Implicit SSL/Explicit SSL (TLS) connection to do user authentication, and you should use your Yahoo email address as the user name for ESMTP authentication. For example: your email is "myid@yahoo.com", and then the user name should be "myid@yahoo.com".

If you want to use implicit SSL connection with Yahoo SMTP server, you must set the port to 465.

Remarks: All of samples in this section are based on first section: Send email in a simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.

[C# - Send Email using Yahoo over Implicit SSL on 465 Port - Example]

The following example codes demonstrate how to send email using Yahoo account in C# over SSL 465 port. To get full sample projects, please refer to Samples section.

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");

            // For example: your email is "myid@yahoo.com", then the user should be "myid@yahoo.com"
            oServer.User = "myid@yahoo.com";
            oServer.Password = "yourpassword";

            // Because yahoo deploys SMTP server on 465 port with implicit SSL connection.
            // So we should change the port to 465.
            oServer.Port = 465;
            
            // detect SSL type automatically
            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);
            }
        }
    }
}

 

[C# - Send Email using Yahoo over Explicit SSL (TLS) on 25 or 587 Port - Example]

The following example codes demonstrate how to send email using Yahoo account in C# over TLS 25 port. To get full sample projects, please refer to Samples section.

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");

            // For example: your email is "myid@yahoo.com", then the user should be "myid@yahoo.com"
            oServer.User = "myid@yahoo.com";
            oServer.Password = "yourpassword";

            // Set 25 port, if you want to use 587 port, please change 25 to 587
            oServer.Port = 25;
            
            // detect SSL/TLS type automatically
            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);
            }
        }
    }
}

 
Next Section

At next section I will introduce how to send email using Hotmail/Live/Office 365 account in C#.

< Prev: Send email using Gmail in C# -> | Next: Send email using Hotmail/Live/Office 365 in C# >

In previous section, I introduced how to send email using Yahoo account. In this section, I will introduce how to send email using Hotmail/Live/Office 365 in C#.

Hotmail/Live SMTP server address is "smtp.live.com". It requires explicit SSL (TLS) connection to do user authentication, and you should use your Hotmail/Live email address as the user name for ESMTP authentication. For example: your email is "liveid@hotmail.com", and then the user name should be "myid@hotmail.com".

Remarks: All of samples in this section are based on first section: Send email in a simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.

[C# - Send Email using Hotmail/Live over Explicit SSL (TLS) on 25 or 587 Port - Example]

The following example codes demonstrate how to send email using Hotmail/Live in C# over TLS 25 or 587 port. To get full sample projects, please refer to Samples section.

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";

            // Set 25 port, if you want to use 587 port, please change 25 to 587
            oServer.Port = 25;

            // detect SSL/TLS connection automatically
            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 using Office 365

First of all, you should go to Office 365 "Outlook" -> "Options" -> "See All Options" -> "Account" -> "My Account" -> "Settings for POP, IMAP, and SMTP access". You will get your Office 365 SMTP server address and port. Then you can use your Office 365 SMTP server, port, user/password in the codes.

By default, Office 365 SMTP server uses 587 port and explicit SSL (TLS) connection.

[C# - Send Email using Office 365 over Explicit SSL (TLS) on 587 Port - Example]

The following example codes demonstrate how to send email using Office 365 in C# over TLS 587 port. To get full sample projects, please refer to Samples section.

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 Offic 365 email address
            oMail.From = "myid@mydomain";
            
            // Set recipient email address
            oMail.To = "support@emailarchitect.net";
            
            // Set email subject
            oMail.Subject = "test email from office 365 account";
            
            // Set email body
            oMail.TextBody = "this is a test email sent from c# project.";

            // Your Office 365 SMTP server address, 
            // You should get it from outlook web access.
            SmtpServer oServer = new SmtpServer("serverid.outlook.com");
            
            // user authentication should use your 
            // email address as the user name. 
            oServer.User = "myid@mydomain";
            oServer.Password = "yourpassword";

            // Set 587 port
            oServer.Port = 587;

            // detect SSL/TLS connection automatically
            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);
            }
        }
    }
}
 
Next Section

At next section I will introduce how to send email without specified SMTP server.

< Prev: Send email using Yahoo in C# | Next: Send email directly without SMTP server(MX DNS lookup) >

In previous section, I introduced how to send email using Hotmail/Live/Office 365 account. In this section, I will introduce how to send email using DNS lookup without specified SMTP server in C#.

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.

Remarks: All of samples in this section are based on first section: Send email in a simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.

[C# - Send Email without SMTP Server (MX record DNS lookup) - Example]

The following example codes demonstrate how to send email using DNS lookup in C#. To get full sample projects, please refer to Samples section.

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.

Remarks

In my solid experience, I don't suggest that you send email directly.

  • If your IP address is dynamic, most SMTP servers reject your connection due to anti-spam policy. We always suggest that your send email by a SMTP server that has a static internet IP address. When you relay email by your SMTP server, because you do user authentication at first before you send email to your SMTP server, so your SMTP server doesn’t reject your connection even your IP address is dynamic. Finally your SMTP server sends email to remote SMTP server. Because your SMTP server has a static IP, the email won’t be rejected by remote SMTP server.

    Send email using DNS lookup in C#
  • If you encountered a temporal SMTP error (4xx), you should retry to send email later. That means you have to write the code to handle retry. So if you have a static IP address, I suggest that you use EASendMail Component + EASendMail Service, EASendMail service can send email directly or send email with specified SMTP server in background and handle delivery retry automatically.

    To learn more detail about EASendMail Serivce, please have a look at Work with EASendMail Service (Email Queuing).

Next Section

At next section I will introduce how to send/compose HTML email in C#.

< Prev: Send email using Hotmail/Live/Office 365 in C# | Next: Send HTML email in C# >

In previous section, I introduced how to send email without SMTP server. In this section, I will introduce how to compose and send HTML email in C#.

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.

Remarks: All of samples in this section are based on first section: Send email in a simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.

[C# - Send HTML Email - Example]

The following example codes demonstrate how to send email in HTML body format in C#. To get full sample projects, please refer to Samples section.

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 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.* samples in EASendMail Installer. Those samples demonstrate how to build a HTML email editor and send HTML email with attachment or embedded images/pictures.

c# html editor

Next Section

At next section I will introduce how to attach file attachment to email message in C#.

< Prev: Send email directly without SMTP server(MX DNS lookup) | Next: Send email with attachment in C# >

In previous section, I introduced how to send HTML email in C#. In this section, I will introduce how to send email with attachment in C#.

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

Remarks: All of samples in this section are based on first section: Send email in a simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.

[C# - Send Email with Attachment - Example]

The following example codes demonstrate how to send email with attachment in C#. To get the full sample projects, please refer to Samples section.

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 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
            {
                // Add attachment from local disk
                oMail.AddAttachment( "d:\\test.pdf" );
                
                // Add 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);
            }
        }
    }
}
 
Next Section

At next section I will introduce how to add embedded images/pictures to email message.

< Prev: Send HTML email in C# | Next: Send email with embedded images in C# >

In previous section, I introduced how to send email with attachment. In this section, I will introduce how to send email with embedded images in C#.

To attach an embedded images 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" />.

Remarks: All of samples in this section are based on first section: Send email in a simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.

[C# - Send Email with Embedded Images - Example]

The following example codes demonstrate how to send email with embedded images in C#. To get full sample projects, please refer to Samples section.

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
            {
                // Add image attachment from local disk
                Attachment oAttachment = oMail.AddAttachment( "d:\\test.gif" );

                // Specifies the attachment as an embedded image
                // contentid can be any string.
                string contentID = "test001@host";
                oAttachment.ContentID = contentID;
                oMail.HtmlBody = "<html><body>this is a <img src=\"cid:"
                     + contentID + "\"> embedded image.</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.

[C# - Send Email with Embedded Images - ImportHtml - Example]

The following example codes demonstrate how to send email using ImportHtml method with embedded images in C#. To get full sample projects, please refer to Samples section.

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
            {
               // Import html body and also import linked image as embedded images.
               oMail.ImportHtml( "<html><body>test <img src=\"test.gif\"> importhtml</body></html>",
	                "c:\\my picture", //test.gif is in c:\\my picture
	                ImportHtmlBodyOptions.ImportLocalPictures | ImportHtmlBodyOptions.ImportCss );

                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);
            }
        }
    }
}
 

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

c# html editor

Next Section

At next section I will introduce how to sign email with digital certificate in C#.

< Prev: Send email with attachment in C# | Next: Send email with digital signature (S/MIME) in C# >

In previous section, I introduced how to send email with embedded images. In this section, I will introduce how to send email with digital signature (S/MIME) in C#.

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.

If you need a free certificate for your email address, you can go to http://www.comodo.com/home/email-security/free-email-certificate.php to apply for one year free email certificate.

Remarks: All of samples in this section are based on first section: Send email in a simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.

[C# - Send Email with Digital Signature (S/MIME) - Example]

The following example codes demonstrate how to send email with digital signature in C#. To get full sample projects, please refer to Samples section.

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);
            }
        }
    }
}
 
Next Section

At next section I will introduce how to encrypt email with digital certificate.

< Prev: Send email with embedded images in C# | Next: Encrypt Email in C# - (S/MIME) >

In previous section, I introduced how to send email with digital signature. In this section, I will introduce how to encrypt email with digital certificate in C#.

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.

Remarks: All of samples in this section are based on first section: Send email in a simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.

[C# - Encrypt Email (S/MIME) - Example]

The following example codes demonstrate how to encrypt email with digital certificate in C#. To get the full samples of EASendMail, please refer to Samples section.

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

Next Section

At next section I will introduce how to send email with event handler.

< Prev: Send email with digtial signature - S/MIME in C# | Next: Send email with event handler in C# >

In previous section, I introduced how to encrypt email with digital certificate. In this section, I will introduce how to send email with event handler in C#.

In previous examples, 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.

Remarks: All of samples in this section are based on first section: Send email in a simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.

[C# - Send Email with Event Handler - Example]

The following example codes demonstrate how to send email with event handler in C#. To get full sample projects, please refer to Samples section.

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);
            }
        }
    }
}

 
Next Section

At next section I will introduce how to send email asynchronously in C#.

< Prev: Encrypt Email in C# - S/MIME | Next: Send email asynchronously in C# >

In previous section, I introduced how to use event handler to monitor the progress. In this section, I will introduce how to send email asynchronously in C#.

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.

Remarks: All of samples in this section are based on first section: Send email in a simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.

[C# - Send Email Asynchronously - Example]

The following example codes demonstrate how to send email asynchronously in C#. To get sample projects, please refer to Samples section.

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);

                // Wait 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);
            }
        }
    }
}
 
Next Section

At next section I will introduce how to send mass emails with multiple threads in C#.

< Prev: Send email with event handler in C# | Next: Send email with multiple threads(mass mail) in C# >

In previous section, I introduced how to use asynchronous mode. In this section, I will introduce how to send mass emails with multiple threads in C#.

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.

Remarks: All of samples in this section are based on first section: Send email in a simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.

[C# - Send Mass Emails with Multiple Threads - Example]

The following example codes demonstrate how to send mass email with multiple threads in C#. To get full sample projects, please refer to Samples section.

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 been 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++;
                }
            }
        }
    }
}

 
Next Section

At next section I will introduce how to send email using EASendMail Service Queue in ASP.NET/C#.

< Prev: Send email asynchronously in C# | Next: Send email using EASendMail Service Queue in C# >

In previous section, I introduced how to send mass emails with multiple threads. In this section, I will introduce how to send email with EASendMail Service Queue in ASP.NET/C#.

EASendMail Service is a light and fast email delivery service which works with EASendMail SMTP Component to enable your application to send mass emails in background queue service. Along with its ability to picking recipients from database in background and sending email in specified datetime, it eases your task in developing featured email application such as newsletter application. We strongly recommend you to use EASendMail Service with your ASP.NET/C# Web Application.

send email using queue in ASP.NET/C#

To work with EASendMail Service, please download EASendMail Service and install it on your server. If you are using web hosting service and you don't have permission to install service on that server, EASendMail service is not suitable for you.

With EASendMail email queue feature, you do not have to code for multiple threadings. EASendMail Service can send email in background with multiple threadings automatically. You just need to adjust the maximum worker threads in EASendMail Service Manager to increase the performance. Please click here to learn more detail about EASendMail Service.

If your networking connection to your SMTP server is not very fast, EASendMail Service is absolutely solution for you. You just need to submit the email to EASendMail service queue, it is very fast because EASendMail service uses shared memory to receive email from EASendMail SMTP Component, and then the service will send email in background service. It is very important to improve the response time for ASP.NET Web Application.

Remarks: All of samples in this section are based on first section: Send email in a simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.

[C# - Send Email with Queue - Example]

The following example codes demonstrate how to send email with EASendMail Service Queue in C#. To get full sample projects, please refer to Samples section.

// The following example codes demonstrate sending email message using email queue
// To get full sample projects, please download and install EASendMail on your machine.
// To run it correctly, please change SMTP server, user, password, sender, recipient value to yours

using System; 
using System.Collections.Generic; 
using System.Text; 

// Add EASendMail namespace
using EASendMail; 

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 ..."); 
                // You just need to change SendMail method to SendMailToQueue method in 
                // your ASP.NET web application, then EASendMail uses queue to send email.
                // SendMailToQueue can be used in windows application as well.
                oSmtp.SendMailToQueue(oServer, oMail); 
                Console.WriteLine("email was sent to queue successfully!"); 
            } 
            catch (Exception ep) 
            { 
                Console.WriteLine("failed to send email with the following error:"); 
                Console.WriteLine(ep.Message); 
            } 
        } 
    } 
} 
Next Section

At next section I will introduce how to send mass emails with EASendMail Service Database Queue in ASP.NET/C#.

< Prev: Send email with multiple threads (Mass Mail) in C# | Next: Send mass emails with EASendMail Service Database Queue in C#>

In previous section, I introduced how to send email EASendMail Service Queue. In this section, I will introduce how to send mass emails with advanced database queue in ASP.NET/C#.

Although EASendMail service provides a faster way to send email in background, but there are thousands of emails in a task, the SendMailToQueue will be invoked for thousands times, obviously it is not effect way.

Therefore, EASendMail service provides a more effective way to send mass emails. In short, you just need to submit your database connection and record set once, EASendMail service will pick up the record set in background and send email to each record one by one. It is very useful to send mass emails in ASP.NET/C# web application.

send email using database queue in C#/ASP.NET

To better understand how to use database queue, we need to create three tables in your SQL database like this:

CREATE TABLE [dbo].[rcpts](
	[uid] [bigint] IDENTITY(1,1) NOT NULL,
	[name] [nvarchar](50) NULL,
	[email] [nvarchar](128) NOT NULL,
 CONSTRAINT [PK_rcpts] PRIMARY KEY CLUSTERED 
(
	[uid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, 
    IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

CREATE TABLE [dbo].[errorlog](
	[uid] [bigint] IDENTITY(1,1) NOT NULL,
	[email] [nvarchar](128) NULL,
	[server] [nvarchar](50) NULL,
	[errorcode] [nvarchar](50) NULL,
	[errordescription] [nvarchar](255) NULL,
 CONSTRAINT [PK_errorlog] PRIMARY KEY CLUSTERED 
(
	[uid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, 
    IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

CREATE TABLE [dbo].[sentlog](
	[uid] [bigint] IDENTITY(1,1) NOT NULL,
	[server] [nvarchar](50) NULL,
	[email] [nvarchar](128) NULL,
 CONSTRAINT [PK_sentlog] PRIMARY KEY CLUSTERED 
(
	[uid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, 
    IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Then insert two records in table 'rcpts' like this:

SQL table sample

Remarks: All of samples in this section are based on first section: Send email in a simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.

[C#/ASP.NET - Send Mass Emails with EASendMail Service Database Queue - Example]

The following example codes demonstrate how to send mass emails using email queue + database in C#/ASP.NET. To get full sample projects, please refer to Samples section.

using System; 
using System.Collections.Generic; 
using System.Text; 

// Add EASendMail namespace
using EASendMail; 

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 email subject
            oMail.Subject = "test email from c# project"; 

            // 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;

            // If you want EASendMail service to send the email after 10 minutes,
            // use the following code.
            // oMail.Date = System.DateTime.Now.AddMinutes( 10 );

// change it to your sql server address, database, user and password.
// The server/instance name syntax used in the server option is the same for all SQL Server connection strings.
// e.g.: Server=serveraddress\\instancename;

            // EASendMail will use the following connection to connect to the database,
            // the syntax is same as ADO connection object. 
            // SQL 2005
            oMail.Headers.ReplaceHeader("X-Data-Connection", 
            "Driver={SQL Native Client};Server=serveraddress;Database=database;Uid=user;Pwd=password;" ); 

// MS SQL Server 2005 Native provider
//oMail.Headers.ReplaceHeader("X-Data-Connection", 
// "Provider=SQLNCLI;Server=serveraddress;Database=database;Uid=user;Pwd=password;" ); 

// MS SQL Server 2008
// oMail.Headers.ReplaceHeader("X-Data-Connection",
//"Driver={SQL Server Native Client 10.0};Server=serveraddress;Database=database;Uid=myUsername;Pwd=myPassword;" );

// MS SQL Server 2008 Native provider
//oMail.Headers.ReplaceHeader("X-Data-Connection", 
// "Provider=SQLNCLI10;Server=serveraddress;Database=database;Uid=user;Pwd=password;" ); 

// MS SQL Server 2012
// oMail.Headers.ReplaceHeader("X-Data-Connection",                             
//"Driver={SQL Server Native Client 11.0};Server=serveraddress;Database=database;Uid=myUsername;Pwd=myPassword;" );

// MS SQL Server 2012 Native provider
//oMail.Headers.ReplaceHeader("X-Data-Connection", 
// "Provider=SQLNCLI11;Server=serveraddress;Database=database;Uid=user;Pwd=password;" ); 

            // EASendMail will select the fields by the following sql statement
            // before sending email,
            // then pick the recipient address from specified field.
            oMail.Headers.ReplaceHeader("X-Sql-Select", "SELECT uid, name, email from rcpts"); 

            // pick "name" field as the recipient name and "email" field as
            // the recipient address.
            // you can also use {$var_srecord:fieldname} to pick any field
            // in X-Sql-Select statement and put it to subject, bodytext, then EASendMail will
            // replace it automatially.

            oMail.Headers.ReplaceHeader("To", "\"{$var_srecord:name}\" <{$var_srecord:email}>"); 
            oMail.Headers.ReplaceHeader("X-Rcpt-To", "{$var_srecord:email}"); 

            // EASendMail service will execute the following sql statement on
            // every email was sent successfully.
            oMail.Headers.ReplaceHeader("X-Sql-OnSentSuccess", 
                "INSERT INTO sentlog ( server, email ) VALUES( '{$var_server}', '{$var_rcptaddr}' )"); 

            // EASendMail service will execute the following sql statement on
            // every email could not be sent.
            oMail.Headers.ReplaceHeader("X-Sql-OnSentError", 
                "INSERT INTO errorlog( email, server, errorcode, errordescription )" + 
                " VALUES( '{$var_rcptaddr}', '{$var_server}', '{$var_errcode}', '{$var_errdesc}' )"); 

            string s = "Hi {$var_srecord:name}, \r\n"; 
            s += "this sample demonstrates how to send email using email queue.\r\n\r\n"; 
            s += "Your id in database is {$var_srecord:uid}.\r\n\r\n"; 
            s += "No matter how many recipients there are, EASendMail "; 
            s += "service will send the email in background.\r\n\r\n"; 
            oMail.TextBody = s; 

            // {$var_srecord:uid} {$var_srecord:name} {$var_srecord:email} in
            // body text will
            // be replaced by EASendMail automatically.

            try 
            { 
                Console.WriteLine("start to send email ..."); 
                // You just need to change SendMail method to SendMailToQueue method in 
                // your ASP.NET web application, then EASendMail uses queue to send email.
                // SendMailToQueue can be used in windows application as well.
                oSmtp.SendMailToQueue(oServer, oMail); 
                Console.WriteLine("email was sent to queue successfully!"); 
            } 
            catch (Exception ep) 
            { 
                Console.WriteLine("failed to send email with the following error:"); 
                Console.WriteLine(ep.Message); 
            } 
        } 
    } 
} 

With above codes, no matter how many records in your table, SendMailToQueue is only invoked once and EASendMail service will pick up records in background and send the email based on each record to recipient one by one. It also inserts the results back to "errorlog" and "sentlog" tables automatically. You can open EASendMail Service Manager to monitor the queue and view Journal -> System Error to check if there is error with your database connection and SQL statement.

Database Server Driver

In X-Data-Connection header, you should specify a database driver to connect database. You can open "Control Panel" -> "Administrative Tools" - > "ODBC Data Sources" - "Drivers" to check current installed database drivers.

odbc drivers

Common SQL Driver Download

If SQL Server is installed on a remote server, and you don't have SQL driver installed on local machine, then you need to download and install corresponding driver on local machine.

SQL Server 2005 Feature Pack - sqlncli.msi
SQL Server 2008 Service Pack 2 Feature Pack - sqlncli.msi
SQL Server 2008 R2 SP2 Feature Pack - sqlncli_xx.msi
SQL Server 2012 SP1 Feature Pack - sqlncli.msi

MS Access Database x64 Driver Download

Microsoft Access Database Engine 2010 Redistributable

See Also

Send Email in SQL Server Stored Procedure - Tutorial

Next Section

At next section I will introduce how to send email using Exchange Web Service (EWS).

< Prev: Send email using EASendMail Service Queue in C# | Next: Send email using Exchange Web Service (EWS) in C# >

In previous section, I introduced how to send mass email with EASendMail SMTP service database queue. In this section, I will introduce how to send email using Exchange Web Service (EWS) in C#.

Exchange Web Services (EWS), an alternative to the MAPI protocol, is a documented SOAP based protocol introduced with Exchange Server 2007. We can use HTTP or HTTPS protocol to send email with Exchange Web Services (EWS) instead of SMTP protocol.

With EASendMail SMTP Component, you do not have to build your EWS SOAP XML request and parse the response. It wraps the SOAP XML and HTTP request automatically. You just need to change the SmtpServer.Protocol property, and then EASendMail uses Web Service protocol to send email. Your server SHOULD be Exchange 2007 or later version; otherwise you cannot use Exchange Web Service (EWS) protocol.

  • SMTP protocol

    Standard SMTP protocol based on TCP/IP, all email servers support this protocol, Exchange Server also supports SMTP protocol. Using SMTP protocol is always recommended.

  • Exchange WebDAV

    Exchange WebDAV is a set of methods based on the HTTP protocol to manage users, messages in Microsoft Exchange Server. We can use HTTP or HTTP/HTTPS protocol to send email with Exchange WebDAV instead of SMTP protocol. But since Exchange 2007, WebDAV service is disabled by default, so I only suggest that you use WebDAV protocol in Exchange 2000/2003.

  • Exchange Web Service (EWS)

    Exchange Web Services (EWS), an alternative to the MAPI protocol, is a documented SOAP based protocol introduced with Exchange Server 2007. We can use HTTP or HTTPS protocol to send email with Exchange Web Services (EWS) instead of SMTP protocol. I only suggest that you use EWS protocol in Exchange 2007/2010/2013 or later version.

Remarks: All of samples in this section are based on first section: Send email in a simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.

[C# - Send Email using Exchange Web Service (EWS) - Example]

The following example codes demonstrate how to send email using Exchange Web Service (EWS) in C#. To get full sample projects, please refer to Samples section.

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 Exchange Server address
            SmtpServer oServer = new SmtpServer("exch.emailarchitect.net");
            
            // Set Exchange Web Service EWS - Exchange 2007/2010/2013
            oServer.Protocol = ServerProtocol.ExchangeEWS;

           // User and password for Exchange authentication     
            oServer.User = "test";
            oServer.Password = "testpassword";
 
            // By default, Exchange Web Service requires SSL connection
            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);
            }
        }
    }
}
                

Exchange Server 2007 EWS Issue

If you send email to Exchange Server 2007 using EWS. You may get an exception: "Client does not have permissions to send as this sender". You should add this line in your code:

// Set sender email address, please change it to yours
oMail.From = "test@emailarchitect.net";

// Add this line
oMail.Headers.RemoveKey( "From" );

That is because Exchange Server 2007 doesn't allow From header in the email message, the From header will be added by Exchange Server automatically.

Manage Send As Permissions in Exchange 2007/2010/2013

If you send email using SMTP protocol and it threw an exception: "Client does not have permissions to send as this sender" with Exchange 2007/2010/2013, please see the following topic:

Manage Send As Permissions for a Mailbox in Exchange 2007
Manage Send As Permissions for a Mailbox in Exchange 2010
Manage Send As Permissions for a Mailbox in Exchange 2013

Next Section

At next section I will introduce how to send email using Exchange WebDAV in C#.

< Prev: Send mass emails with EASendMail Service Database Queue in C# | Next: Send email using Exchange WebDAV in C# >

In previous section, I introduced how to send email using Exchange Web Service - EWS. In this section, I will introduce how to send email using Exchange WebDAV in C#.

Exchange WebDAV is a set of methods based on the HTTP protocol to manage users, messages in Microsoft Exchange Server. We can use HTTP or HTTPS protocol to send email with Exchange WebDAV instead of SMTP protocol.

With EASendMail SMTP Component, you do not have to build your WebDAV request and parse the response. It wraps the WebDAV HTTP request automatically. You just need to change the SmtpServer.Protocol property, and then EASendMail uses WebDAV protocol to send email. Your server SHOULD be Exchange 2000 or 2003 version; otherwise you cannot use Exchange WebDAV protocol. Although Exchange 2007 still supports WebDAV protocol, but the default status of WebDAV in Exchange 2007 is disabled, so you should use Exchange Web Service protocol with Exchange 2007 or later version.

  • SMTP protocol

    Standard SMTP protocol based on TCP/IP, all email servers support this protocol, Exchange Server also supports SMTP protocol. Using SMTP protocol is always recommended.

  • Exchange WebDAV

    Exchange WebDAV is a set of methods based on the HTTP protocol to manage users, messages in Microsoft Exchange Server. We can use HTTP or HTTP/HTTPS protocol to send email with Exchange WebDAV instead of SMTP protocol. But since Exchange 2007, WebDAV service is disabled by default, so I only suggest that you use WebDAV protocol in Exchange 2000/2003.

  • Exchange Web Service (EWS)

    Exchange Web Services (EWS), an alternative to the MAPI protocol, is a documented SOAP based protocol introduced with Exchange Server 2007. We can use HTTP or HTTPS protocol to send email with Exchange Web Services (EWS) instead of SMTP protocol. I only suggest that you use EWS protocol in Exchange 2007/2010/2013 or later version.

Remarks: All of samples in this section are based on first section: Send email in a simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.

[C# - Send Email using Exchange WebDAV - Example]

The following example codes demonstrate how to send email using Exchange WebDAV in C#. To get full sample projects, please refer to Samples section.

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 Exchange Server address
            SmtpServer oServer = new SmtpServer("exch.emailarchitect.net");

            // Set Exchange WebDAV protocol - Exchange 2000/2003
            oServer.Protocol = ServerProtocol.ExchangeWebDav;

            // User and password for Exchange authentication     
            oServer.User = "test";
            oServer.Password = "testpassword";
 
            // If your Exchange WebDAV 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);
            }
        }
    }
}
                
See Also

< Prev: Send email using Exchange Web Service | Next: C# - Send Email using SMTP/EWS/WebDAV - Sample Projects >

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

All the samples locate at "EASendMail Installation Folder". They all demonstrate User authentication, SSL connection and Dns Lookup.
.NET Framework Sample Projects:
Samples_VS2003 requires .NET 1.1 or later version.
Samples_VS2008 requires .NET 2.0 or later version.
Samples_VS2010 requires .NET 4.0 or later version.
Samples_VS2012 requires .NET 4.5 or later version.

Project Version

All the samples are built with Visual Studio 2003/2008/2010/2012. If you use different (elder) version of Visual Studio, those projects may not be openned properly. In this case, you need to create a new project in your Visual Studio and copy the code in the sample to overwrite your code. For example, if you can't open simple.vb project with your Visual Studio, create a project with your Visual Studio, then copy form1.vb to overwrite the form1.vb in your project. Re-open your project, and finally add the reference of EASendMail.dll to your project.

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.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.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.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.
Windows Store App Projects (Windows 8 Metro Style):
Samples_Windows8 requires Windows 8 + Visual Studio 2012 or later version.
simple.vb Send text/plain or html email from Visual Basic.NET. This sample also demonstrates file attachments, embedded images. (VB, XAML, WPF, Windows 8 Store App Runtime)
simple.csharp Send text/plain or html email from C#. This sample also demonstrates file attachments, embedded images. (C#, XAML, WPF, Windows 8 Store App Runtime)
simple.js Send text/plain or html email from Javascript. This sample also demonstrates file attachments, embedded images. (Javascript, HTML5, Windows 8 Store App Runtime)
mass.vb Send text/plain or html email from VB.NET with multiple threadings. This sample also demonstrates file attachments, embedded images. (VB, XAML, WPF, Windows 8 Store App Runtime)
mass.csharp Send text/plain or html email from C# with multiple threadings. This sample also demonstrates file attachments, embedded images. (C#, XAML, WPF, Windows 8 Store App Runtime)
mass.js SSend text/plain or html email from Javascript with multiple threadings. This sample also demonstrates file attachments, embedded images. (Javascript, HTML5, Windows 8 Store App Runtime)
.ActiveX Object/COM Sample Projects:
Samples_VB6 requires Visual Basic 6.0.
Samples_Delphi requires Delphi 7.0 or later version.
Samples_VC requires Visual Studio 2008 (C++) or later version.
Samples_ASP requires IIS.
Samples_Script - VBScript/Javascript.
Samples_MSSQL - Microsoft SQL Server.
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
simple.vb6 Send text/plain email from Visual Basic 6.0. This sample also demonstrates digital signature, email encryption. (VB6) - ActiveX/COM
simple.delphi Send text/plain email from Delphi. This sample also demonstrates digital signature, email encryption. (Delphi) - ActiveX/COM
simple.vcNative Send text/plain email from Visual C++. This sample also demonstrates digital signature, email encryption. (Visual C++) - ActiveX/COM
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
html.delphi Send text/html email from Delphi. 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.vcNative Send email by FastSender with multiple threadings. This sample also demonstrates email address validating. (Visual C++) - ActiveX/COM
mass.delphi Send email by FastSender with multiple threadings. This sample also demonstrates email address validating. (Delphi) - ActiveX/COM
Samples_MSSQL Send email from MS SQL Server stored procedure.

Free Email Support

Not enough? Please contact our technical support team.

Support@EmailArchitect.NET

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 Gmail, Hotmail or Yahoo email account is recommended.

See Also

< Prev: Tutorial Index

Send Email - C# - VB6 - Visual Basic - VC++ - C++/CLI - Delphi

Retrieve Email and Parse Email - C# - VB6 - Visual Basic - VC++ - C++/CLI - Delphi

Email Solution - Email Server - DomainKeys and DKIM - Disclaimer

2003 - 2014 © Copyright AdminSystem Software Limited. All rights reserved.   About us     Follow emailarchitect on Twitter   Follow emailarchitect on facebook