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
Sections:
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.
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.
Install from NuGet
You can also install the run-time assembly by NuGet. Run the following command in the NuGet Package Manager Console:
Install-Package EASendMail
Note
If you install it by NuGet, no sample projects are installed, only .NET assembly is installed.
To use EASendMail SMTP Component in your project, the first step is “Add reference
of EASendMail to your project”. Please create or open your project with Visual Studio
and go to menu
-> Project
-> Add Reference
-> .NET
-> Browse...
, and
select the Installation Path\Lib\net[version]\EASendMail.dll
from local disk, click Open
-> OK
, the reference
will be added to the project, and you can start to use it to send email in the project.
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, 4.6.1, .NET Core 3.1, .NET 5.0, .NET Standard 2.0 and .NET Compact Framework 2.0, 3.5.
File | .NET Framework Version |
Lib\net20\EASendMail.dll |
Built with .NET Framework 2.0
It requires .NET Framework 2.0, 3.5 or later version. |
Lib\net40\EASendMail.dll |
Built with .NET Framework 4.0
It requires .NET Framework 4.0 or later version. |
Lib\net45\EASendMail.dll |
Built with .NET Framework 4.5
It requires .NET Framework 4.5 or later version. |
Lib\net461\EASendMail.dll |
Built with .NET Framework 4.6.1
It requires .NET Framework 4.6.1 or later version. |
Lib\netcoreapp3.1\EASendMail.dll |
Built with .NET Core 3.1
It requires .NET Core 3.1 or later version. |
Lib\net5.0\EASendMail.dll |
Built with .NET 5.0
It requires .NET 5.0 or later version. |
Lib\netstandard2.0\EASendMail.dll |
Built with .NET Standard 2.0
It requires .NET Standard 2.0 or later version. |
Lib\net20-cf\EASendMail.dll |
Built with .NET Compact Framework 2.0
It requires .NET Compact Framework 2.0, 3.5 or later version. |
Lib\net35-cf\EASendMail.dll |
Built with .NET Compact Framework 3.5
It requires .NET Compact Framework 3.5 or later version. |
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.
Note
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)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// 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";
// SMTP server address
SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");
// User and password for ESMTP authentication
oServer.User = "test@emailarchitect.net";
oServer.Password = "testpassword";
// Most mordern SMTP servers require SSL/TLS connection now.
// ConnectTryTLS means if server supports SSL/TLS, SSL/TLS will be used automatically.
oServer.ConnectType = SmtpConnectType.ConnectTryTLS;
// If your SMTP server uses 587 port
// oServer.Port = 587;
// If your SMTP server requires SSL/TLS connection on 25/587/465 port
// oServer.Port = 25; // 25 or 587 or 465
// oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
Console.WriteLine("start to send email ...");
SmtpClient oSmtp = new SmtpClient();
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.
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.
TLS is the successor of SSL, more and more SMTP servers require TLS 1.2 encryption now.
If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2
,
and you got connection error with SSL/TLS connection,
you need to enable TLS 1.2 protocol in your operating system like this:
Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012
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.
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, 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:
report@emailarchitect.net
.sender@emailarchitect.net
on behalf of from@adminsystem.com
.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";
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;
When you send email in above simple C# project, if it threw an exception, please have a look at the following tips:
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.
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.
Note
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:
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.
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.
TThis error means user authentication is failed, you should check whether you input correct user/password. Password is always case-sensitive.
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.
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;
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.
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);
}
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 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
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:
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.
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#.
Sections:
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
EASendMail SMTP component supports both ways. The connection can be specified by EASendMail.SmtpConnectType enumeration. Please see the following example code
TLS is the successor of SSL, more and more SMTP servers require TLS 1.2 encryption now.
If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2
,
and you got connection error with SSL/TLS connection,
you need to enable TLS 1.2 protocol in your operating system like this:
Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012
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;
// If server supports SSL/TLS, then SSL/TLS is used, otherwise normal TCP is used.
SmtpServer oServer = new SmtpServer("localhost 25");
oServer.ConnectType = SmtpConnectType.ConnectTryTLS;
SmtpServer oServer = new SmtpServer("localhost 587");
oServer.ConnectType = SmtpConnectType.ConnectTryTLS;
Note
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.
The following example codes demonstrate how to send email over SSL connection on 465 port.
Note
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)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
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");
// User and password for ESMTP authentication
oServer.User = "test@emailarchitect.net";
oServer.Password = "testpassword";
// Set SSL 465 port
oServer.Port = 465;
// Set direct SSL connection, you can also use ConnectSSLAuto
oServer.ConnectType = SmtpConnectType.ConnectDirectSSL;
Console.WriteLine("start to send email ...");
SmtpClient oSmtp = new SmtpClient();
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);
}
}
}
}
The following example codes demonstrate how to send email over TLS (STARTTLS command, Explicit SSL) connection on 25 port.
Note
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)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
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");
// User and password for ESMTP authentication
oServer.User = "test@emailarchitect.net";
oServer.Password = "testpassword";
// Set 25 port, if your server uses 587 port, please change 25 to 587
oServer.Port = 25;
// Set TLS connection, you can also use ConnectSSLAuto
oServer.ConnectType = SmtpConnectType.ConnectSTARTTLS;
Console.WriteLine("start to send email ...");
SmtpClient oSmtp = new SmtpClient();
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.
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#.
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#.
Sections:
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.
Server | Port | SSL/TLS |
smtp.gmail.com | 25, 587 | TLS |
smtp.gmail.com | 465 | SSL |
To help keep your account secure, starting May 30, 2022, Google will no longer support the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password.
Therefore, you should sign in using App Passwords.
An App Password
is a 16-digit passcode that gives a less secure app or device permission
to access your Google Account. App Passwords
can only be used with accounts that have 2-Step Verification turned on.
You need to use App Password
instead of the user password for user authentication.
Another solution is Gmail OAUH, please see Gmail SMTP OAUTH section.
Note
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.
The following example codes demonstrate how to send email using Gmail account over SSL in C#.
Note
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)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// Your gmail email address
oMail.From = "gmailid@gmail.com";
// Set recipient email address
oMail.To = "support@emailarchitect.net";
// Set email subject
oMail.Subject = "test email from gmail account";
// Set email body
oMail.TextBody = "this is a test email sent from c# project with gmail.";
// Gmail SMTP server address
SmtpServer oServer = new SmtpServer("smtp.gmail.com");
// Gmail user authentication
// For example: your email is "gmailid@gmail.com", then the user should be the same
oServer.User = "gmailid@gmail.com";
// Create app password in Google account
// https://support.google.com/accounts/answer/185833?hl=en
oServer.Password = "your app password";
// Set 465 port
oServer.Port = 465;
// detect SSL/TLS automatically
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
Console.WriteLine("start to send email over SSL ...");
SmtpClient oSmtp = new SmtpClient();
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);
}
}
}
}
The following example codes demonstrate how to send email using Gmail account over TLS in C#.
Note
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)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// Your gmail email address
oMail.From = "gmailid@gmail.com";
// Set recipient email address
oMail.To = "support@emailarchitect.net";
// Set email subject
oMail.Subject = "test email from gmail account";
// Set email body
oMail.TextBody = "this is a test email sent from c# project with gmail.";
// Gmail SMTP server address
SmtpServer oServer = new SmtpServer("smtp.gmail.com");
// Gmail user authentication
// For example: your email is "gmailid@gmail.com", then the user should be the same
oServer.User = "gmailid@gmail.com";
// Create app password in Google account
// https://support.google.com/accounts/answer/185833?hl=en
oServer.Password = "your app password";
// Set 587 port, if you want to use 25 port, please change 587 5o 25
oServer.Port = 587;
// detect SSL/TLS automatically
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
Console.WriteLine("start to send email over SSL ...");
SmtpClient oSmtp = new SmtpClient();
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);
}
}
}
}
The Gmail IMAP and SMTP servers have been extended to support authorization via the industry-standard OAuth 2.0 protocol. Using OAUTH protocol, user can do authentication by Gmail Web OAuth instead of inputting user and password directly in application.
Google will disable traditional user authentication in the future, switching to Google OAuth is strongly recommended now.
TLS is the successor of SSL, more and more SMTP servers require TLS 1.2 encryption now.
If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2
,
and you got connection error with SSL/TLS connection,
you need to enable TLS 1.2 protocol in your operating system like this:
Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012
Next Section
At next section I will introduce how to send email using Yahoo account 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#.
Sections:
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.
Server | Port | SSL/TLS |
smtp.mail.yahoo.com | 25, 587 | TLS |
smtp.mail.yahoo.com | 465 | SSL |
Note
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.
Important
If you got authentication error, you need to enable Allowing less secure apps in your Yahoo account. Or you can generate App Passwords and use this app password instead of your user password.
Although Yahoo supports OAUTH, but it doesn’t provide mail permission, so OAUTH is not a solution for Yahoo mail.
The following example codes demonstrate how to send email using Yahoo account in C# over SSL 465 port.
Note
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)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// 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;
Console.WriteLine("start to send email over SSL ...");
SmtpClient oSmtp = new SmtpClient();
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);
}
}
}
}
The following example codes demonstrate how to send email using Yahoo account in C# over TLS 25 port.
Note
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)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// 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;
Console.WriteLine("start to send email over SSL ...");
SmtpClient oSmtp = new SmtpClient();
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);
}
}
}
}
TLS is the successor of SSL, more and more SMTP servers require TLS 1.2 encryption now.
If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2
,
and you got connection error with SSL/TLS connection,
you need to enable TLS 1.2 protocol in your operating system like this:
Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012
Next Section
At next section I will introduce how to send email using Hotmail/Outlook/Live/Office 365 account 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#.
Sections:
Hotmail/Live/Outlook.com SMTP server address is smtp.office365.com
. It requires explicit SSL (TLS)
connection to do user authentication, and you should use your Hotmail/Live/Outlook.com email
address as the user name for ESMTP authentication. For example: your email is myid@hotmail.com
,
and then the user name should be myid@hotmail.com
.
Server | Port | SSL/TLS |
smtp.office365.com | 25, 587 | TLS |
Note
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.
The following example codes demonstrate how to send email using Hotmail/Live/Outlook.com in C# over TLS 25 or 587 port.
Note
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)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// 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.office365.com");
// Hotmail user authentication should use your
// email address as the user name.
oServer.User = "liveid@hotmail.com";
// If you got authentication error, try to create an app password instead of your user password.
// https://support.microsoft.com/en-us/account-billing/using-app-passwords-with-apps-that-don-t-support-two-step-verification-5896ed9b-4263-e681-128a-a6f2979a7944
oServer.Password = "your password or app password";
// Set 587 port, if you want to use 25 port, please change 587 to 25
oServer.Port = 587;
// detect SSL/TLS connection automatically
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
Console.WriteLine("start to send email over SSL...");
SmtpClient oSmtp = new SmtpClient();
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 your account enabled two-factor authentication, you cannot login your account by normal user authentication, you should use SMTP OAUTH or App Password.
Microsoft Live SMTP servers (Hotmail, Oultook personal account) have been extended to support authorization via the industry-standard OAuth 2.0 protocol. Using OAUTH protocol, user can do authentication by Microsoft Web OAuth instead of inputting user and password directly in application.
Microsoft will disable traditional user authentication in the future, switching to Microsoft OAuth (Modern Authentication) is strongly recommended now.
Or you can generate App Passwords and use this app password instead of your user password.
Office 365 SMTP server uses 587 port and explicit SSL (TLS) connection.
Server | Port | SSL/TLS |
smtp.office365.com | 25, 587 (recommended) | TLS |
If your account enabled two-factor authentication, you cannot login your account by normal user authentication,
you should create an App Passwords and
use this App Password
instead of the user password.
You should also check if authenticated client SMTP submission (SMTP AUTH)
is enabled:
Enable or disable authenticated client SMTP submission (SMTP AUTH) in Exchange Online.
The following example codes demonstrate how to send email using Office 365 in C# over TLS 587 port.
Note
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)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// 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("smtp.office365.com");
// user authentication should use your
// email address as the user name.
oServer.User = "myid@mydomain";
// If you got authentication error, try to create an app password instead of your user password.
// https://support.microsoft.com/en-us/account-billing/using-app-passwords-with-apps-that-don-t-support-two-step-verification-5896ed9b-4263-e681-128a-a6f2979a7944
oServer.Password = "your password or app password";
// Set 587 port
oServer.Port = 587;
// detect SSL/TLS connection automatically
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
Console.WriteLine("start to send email over SSL...");
SmtpClient oSmtp = new SmtpClient();
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 your account enabled two-factor authentication, you cannot login your account by normal user authentication, you should use SMTP/EWS/Ms Graph API OAUTH or App Password.
Microsoft Office365 SMTP/EWS/Ms Graph API servers have been extended to support authorization via the industry-standard OAuth 2.0 protocol. Using OAUTH protocol, user can do authentication by Microsoft Web OAuth instead of inputting user and password directly in application.
Microsoft will disable traditional user authentication in the future, switching to Microsoft OAuth (Modern Authentication) is strongly recommended now.
Or you can generate App Passwords and use this app password instead of your user password.
Next Section
At next section I will introduce how to send email without specified SMTP server.
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.
Note
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.
The following example codes demonstrate how to send email using DNS lookup in C#.
Note
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)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// 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
Console.WriteLine("start to send email directly ...");
SmtpClient oSmtp = new SmtpClient();
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.
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#.
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.
Note
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.
The following example codes demonstrate how to send email in HTML body format in C#.
Note
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)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// 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
oServer.User = "test@emailarchitect.net";
oServer.Password = "testpassword";
// Most mordern SMTP servers require SSL/TLS connection now.
// ConnectTryTLS means if server supports SSL/TLS, SSL/TLS will be used automatically.
oServer.ConnectType = SmtpConnectType.ConnectTryTLS;
// If your SMTP server uses 587 port
// oServer.Port = 587;
// If your SMTP server requires SSL/TLS connection on 25/587/465 port
// oServer.Port = 25; // 25 or 587 or 465
// oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
Console.WriteLine("start to send HTML email ...");
SmtpClient oSmtp = new SmtpClient();
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:
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.
Next Section
At next section I will introduce how to attach file attachment to email message 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.
Note
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.
The following example codes demonstrate how to send email with attachment in C#.
Note
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)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// 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>";
// 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");
// Your SMTP server address
SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");
// User and password for ESMTP authentication
oServer.User = "test@emailarchitect.net";
oServer.Password = "testpassword";
// Most mordern SMTP servers require SSL/TLS connection now.
// ConnectTryTLS means if server supports SSL/TLS, SSL/TLS will be used automatically.
oServer.ConnectType = SmtpConnectType.ConnectTryTLS;
// If your SMTP server uses 587 port
// oServer.Port = 587;
// If your SMTP server requires SSL/TLS connection on 25/587/465 port
// oServer.Port = 25; // 25 or 587 or 465
// oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
Console.WriteLine("start to send email with attachment ...");
SmtpClient oSmtp = new SmtpClient();
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.
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#.
Sections:
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"
/>
.
Note
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.
The following example codes demonstrate how to send email with embedded images in C#.
Note
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)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// 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";
// 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>";
// Your SMTP server address
SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");
// User and password for ESMTP authentication
oServer.User = "test@emailarchitect.net";
oServer.Password = "testpassword";
// Most mordern SMTP servers require SSL/TLS connection now.
// ConnectTryTLS means if server supports SSL/TLS, SSL/TLS will be used automatically.
oServer.ConnectType = SmtpConnectType.ConnectTryTLS;
// If your SMTP server uses 587 port
// oServer.Port = 587;
// If your smtp server requires SSL/TLS connection, please use
// oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
Console.WriteLine("start to send email with embedded image...");
SmtpClient oSmtp = new SmtpClient();
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.
The following example codes demonstrate how to send email using ImportHtml method with embedded images in C#.
Note
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)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// 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";
// 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 );
// Your SMTP server address
SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");
// User and password for ESMTP authentication
oServer.User = "test@emailarchitect.net";
oServer.Password = "testpassword";
// Most mordern SMTP servers require SSL/TLS connection now.
// ConnectTryTLS means if server supports SSL/TLS, SSL/TLS will be used automatically.
oServer.ConnectType = SmtpConnectType.ConnectTryTLS;
// If your SMTP server uses 587 port
// oServer.Port = 587;
// If your SMTP server requires SSL/TLS connection on 25/587/465 port
// oServer.Port = 25; // 25 or 587 or 465
// oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
Console.WriteLine("start to send email with embedded image...");
SmtpClient oSmtp = new SmtpClient();
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.
Next Section
At next section I will introduce how to sign email with digital certificate 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#.
Sections:
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”.
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.
Note
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.
The following example codes demonstrate how to send email with digital signature in C#.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using EASendMail; //add EASendMail namespace
namespace mysendemail
{
class Program
{
static X509Certificate2 _findCertificate(string storeName, string emailAddress)
{
X509Certificate2 cert = null;
X509Store store = new X509Store(storeName, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certfiicates = store.Certificates.Find(X509FindType.FindBySubjectName, emailAddress, true);
if (certfiicates.Count > 0)
{
cert = certfiicates[0];
}
store.Close();
return cert;
}
static void Main(string[] args)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// 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";
X509Certificate2 signerCertificate = _findCertificate("My", oMail.From.Address);
if (signerCertificate == null)
throw new Exception("No signer certificate found for " + oMail.From.Address + "!");
oMail.From.Certificate2 = signerCertificate;
// You can also load the signer certificate from a pfx file.
/* string pfxPath = "D:\\TestCerts\\signer.pfx";
X509Certificate2 signerCertFromPfx = new X509Certificate2(pfxPath,
"nosecret",
X509KeyStorageFlags.Exportable | X509KeyStorageFlags.UserKeySet);
oMail.From.Certificate2 = signerCertFromPfx;
*/
// If you use it in web application,
// please use X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet
// If you use it in .NET core application
// please use X509KeyStorageFlags.Exportable | X509KeyStorageFlags.EphemeralKeySet
// Your smtp server address
SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");
// User and password for ESMTP authentication
oServer.User = "test@emailarchitect.net";
oServer.Password = "testpassword";
// Most mordern SMTP servers require SSL/TLS connection now.
// ConnectTryTLS means if server supports SSL/TLS, SSL/TLS will be used automatically.
oServer.ConnectType = SmtpConnectType.ConnectTryTLS;
// If your SMTP server uses 587 port
// oServer.Port = 587;
// If your SMTP server requires SSL/TLS connection on 25/587/465 port
// oServer.Port = 25; // 25 or 587 or 465
// oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
Console.WriteLine("start to send email with digital signature ...");
SmtpClient oSmtp = new SmtpClient();
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 use SmtpMail.SignatureHashAlgorithm property to set MD5, SHA1, SHA256, SHA384 or SHA512 signature algorithm. SHA256 is recommended.
RSASSA-PSS Signature for EDIFACT
If you need to use RSASSA-PSS signature scheme based on EDIFACT rule, you need a special version of EASendMail, please have a look at this topic:
RSASSA-PSS + RSA-OAEP Encryption with SHA256
Next Section
At next section I will introduce how to encrypt email with digital certificate.
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.
Note
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.
The following example codes demonstrate how to encrypt email with digital certificate in C#.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using EASendMail; //add EASendMail namespace
namespace mysendemail
{
class Program
{
static X509Certificate2 _findCertificate(string storeName, string emailAddress)
{
X509Certificate2 cert = null;
X509Store store = new X509Store(storeName, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certfiicates = store.Certificates.Find(X509FindType.FindBySubjectName, emailAddress, true);
if (certfiicates.Count > 0)
{
cert = certfiicates[0];
}
store.Close();
return cert;
}
static void Main(string[] args)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// 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";
X509Certificate2 signerCertificate = _findCertificate("My", oMail.From.Address);
if (signerCertificate == null)
throw new Exception("No signer certificate found for " + oMail.From.Address + "!");
oMail.From.Certificate2 = signerCertificate;
// You can also load the signer certificate from a pfx file.
/* string pfxPath = "D:\\TestCerts\\signer.pfx";
X509Certificate2 signerCertFromPfx = new X509Certificate2(pfxPath,
"nosecret",
X509KeyStorageFlags.Exportable | X509KeyStorageFlags.UserKeySet);
oMail.From.Certificate2 = signerCertFromPfx;
*/
// If you use it in web application,
// please use X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet
// If you use it in .NET core application
// please use X509KeyStorageFlags.Exportable | X509KeyStorageFlags.EphemeralKeySet
int count = oMail.To.Count;
for (int i = 0; i < count; i++)
{
MailAddress oAddress = oMail.To[i] as MailAddress;
X509Certificate2 encryptCert = _findCertificate("AddressBook", oAddress.Address);
if (encryptCert == null)
encryptCert = _findCertificate("My", oAddress.Address);
if (encryptCert == null)
throw new Exception("No encryption certificate found for " + oAddress.Address + "!");
oAddress.Certificate2 = encryptCert;
// You can also load the encryptor certificate from a cer file like this
/*
string cerPath = "D:\\TestCerts\\encryptor.cer";
X509Certificate2 encryptCertFromFile = new X509Certificate2(cerPath);
oAddress.Certificate2 = encryptCertFromFile;
*/
}
// 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";
// Most mordern SMTP servers require SSL/TLS connection now.
// ConnectTryTLS means if server supports SSL/TLS, SSL/TLS will be used automatically.
oServer.ConnectType = SmtpConnectType.ConnectTryTLS;
// If your SMTP server uses 587 port
// oServer.Port = 587;
// If your SMTP server requires SSL/TLS connection on 25/587/465 port
// oServer.Port = 25; // 25 or 587 or 465
// oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
Console.WriteLine("start to send encrypted email ...");
SmtpClient oSmtp = new SmtpClient();
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:
You can use SmtpMail.EncryptionAlgorithm property to set RC2, RC4, 3DES, AES128, AES192 or AES256 encryption algorithm. RSAES-OAEP (AES128, AES192 and AES256) is recommended.
RSA-OAEP Encryption with SHA256 HASH
If you need to use RSA-OAEP encryption with sha256 scheme based on EDIFACT rule, please have a look at this topic:
RSASSA-PSS + RSA-OAEP Encryption with SHA256 hash algorithm
Next Section
At next section I will introduce how to send email with event handler.
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.
Note
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.
The following example codes demonstrate how to send email with event handler in C#.
Note
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
{
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)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// 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";
// Most mordern SMTP servers require SSL/TLS connection now.
// ConnectTryTLS means if server supports SSL/TLS, SSL/TLS will be used automatically.
oServer.ConnectType = SmtpConnectType.ConnectTryTLS;
// If your SMTP server uses 587 port
// oServer.Port = 587;
// If your SMTP server requires SSL/TLS connection on 25/587/465 port
// oServer.Port = 25; // 25 or 587 or 465
// oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
Console.WriteLine("start to send email ...");
SmtpClient oSmtp = new SmtpClient();
// 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);
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#.
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#.
Sections:
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.
Note
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.
The following example codes demonstrate how to send email asynchronously in C#.
Note
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)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// 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
oServer.User = "test@emailarchitect.net";
oServer.Password = "testpassword";
// Most mordern SMTP servers require SSL/TLS connection now.
// ConnectTryTLS means if server supports SSL/TLS, SSL/TLS will be used automatically.
oServer.ConnectType = SmtpConnectType.ConnectTryTLS;
// If your SMTP server uses 587 port
// oServer.Port = 587;
// If your SMTP server requires SSL/TLS connection on 25/587/465 port
// oServer.Port = 25; // 25 or 587 or 465
// oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
Console.WriteLine("start to send email in asynchronous mode...");
SmtpClient oSmtp = new SmtpClient();
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);
}
}
}
}
SmtpClient also supports task asynchronous programming model (TAP), you can use async and await to send email asynchronously.
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using EASendMail; //add EASendMail namespace
namespace mysendemail
{
class Program
{
static async Task Main(string[] args)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// 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
oServer.User = "test@emailarchitect.net";
oServer.Password = "testpassword";
// Most mordern SMTP servers require SSL/TLS connection now.
// ConnectTryTLS means if server supports SSL/TLS, SSL/TLS will be used automatically.
oServer.ConnectType = SmtpConnectType.ConnectTryTLS;
// If your SMTP server uses 587 port
// oServer.Port = 587;
// If your SMTP server requires SSL/TLS connection on 25/587/465 port
// oServer.Port = 25; // 25 or 587 or 465
// oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
Console.WriteLine("start to send email in asynchronous mode...");
SmtpClient oSmtp = new SmtpClient();
await oSmtp.SendMailAsync(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 mass emails with multiple threads 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.
Note
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.
The following example codes demonstrate how to send mass email with multiple threads in C#.
Note
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)
{
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
oServer.User = "test@emailarchitect.net";
oServer.Password = "testpassword";
// Most mordern SMTP servers require SSL/TLS connection now.
// ConnectTryTLS means if server supports SSL/TLS, SSL/TLS will be used automatically.
oServer.ConnectType = SmtpConnectType.ConnectTryTLS;
// If your SMTP server uses 587 port
// oServer.Port = 587;
// If your SMTP server requires SSL/TLS connection on 25/587/465 port
// oServer.Port = 25; // 25 or 587 or 465
// 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++;
}
}
}
}
}
I strongly suggest that you have a look at Mass sample project, it uses a thread pool to send mass emails and support throttling control.
Note
To get the full sample projects, please refer to Samples section.
Next Section
At next section I will introduce how to send email using EASendMail Service Queue in ASP.NET/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.
Important
To work with EASendMail Service, please download EASendMail and EASendMail Service at first, and then install both on your machine. 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.
Note
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.
The following example codes demonstrate how to send email with EASendMail Service Queue in C#.
Note
To get the 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.Text;
// Add EASendMail namespace
using EASendMail;
namespace mysendemail
{
class Program
{
static void Main(string[] args)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// 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
oServer.User = "test@emailarchitect.net";
oServer.Password = "testpassword";
// Most mordern SMTP servers require SSL/TLS connection now.
// ConnectTryTLS means if server supports SSL/TLS, SSL/TLS will be used automatically.
oServer.ConnectType = SmtpConnectType.ConnectTryTLS;
// If your SMTP server uses 587 port
// oServer.Port = 587;
// If your SMTP server requires SSL/TLS connection on 25/587/465 port
// oServer.Port = 25; // 25 or 587 or 465
// oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
Console.WriteLine("start to send email ...");
SmtpClient oSmtp = new SmtpClient();
// 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);
// If you want to use SMTP server setting in EASendMail Service Manager, use
// oSmtp.SendMailToQueue(null, 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#.
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#.
Sections:
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.
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:
Note
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.
The following example codes demonstrate how to send mass emails using email queue + database in C#/ASP.NET.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Text;
// Add EASendMail namespace
using EASendMail;
namespace mysendemail
{
class Program
{
static void Main(string[] args)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// Set sender email address, please change it to yours
oMail.From = "test@emailarchitect.net";
// Set email subject
oMail.Subject = "test email from c# project";
// 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.
// Your SMTP server address
SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");
// User and password for ESMTP authentication
oServer.User = "test@emailarchitect.net";
oServer.Password = "testpassword";
// Most mordern SMTP servers require SSL/TLS connection now.
// ConnectTryTLS means if server supports SSL/TLS, SSL/TLS will be used automatically.
oServer.ConnectType = SmtpConnectType.ConnectTryTLS;
// If your SMTP server uses 587 port
// oServer.Port = 587;
// If your SMTP server requires SSL/TLS connection on 25/587/465 port
// oServer.Port = 25; // 25 or 587 or 465
// oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
Console.WriteLine("start to send email ...");
SmtpClient oSmtp = new SmtpClient();
// 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);
// If you want to use SMTP server setting in EASendMail Service Manager, use
// oSmtp.SendMailToQueue(null, 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.
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.
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.
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).
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#.
Sections:
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/2016 or later version. Office365 also supports EWS very well.
Note
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.
The following example codes demonstrate how to send email using Exchange Web Service (EWS) in C#.
Note
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)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// 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/Office365 server address
SmtpServer oServer = new SmtpServer("exch.emailarchitect.net");
// Set Exchange Web Service EWS - Exchange 2007/2010/2013/2016/Office365
oServer.Protocol = ServerProtocol.ExchangeEWS;
// User and password for Exchange authentication
oServer.User = "test@emailarchitect.net";
oServer.Password = "testpassword";
// By default, Exchange Web Service requires SSL connection
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
Console.WriteLine("start to send email ...");
SmtpClient oSmtp = new SmtpClient();
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 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.
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:
Next Section
At next section I will introduce how to 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.
Note
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.
The following example codes demonstrate how to send email using Exchange WebDAV in C#.
Note
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)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// 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;
Console.WriteLine("start to send email ...");
SmtpClient oSmtp = new SmtpClient();
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
Total sample projects in EASendMail SMTP Component installation package.
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
.
Most of sample projects demonstrate file attachment, embedded images, S/MIME, user authentication, SSL/TLS connection and Dns lookup.
C#, VB, JScript\Simple | Send a simple email from ASP.NET form. |
C#, VB, JScript\SimpleQueue | Send email from ASP.NET to EASendMail Service. |
C#, VB\GmailOauth | Send email using Gmail OAUTH/XOAUTH2. |
C#, VB, JScript\AdvancedQueueWithDatabase | Send email from ASP.NET to EASendMail Service, background service will select recipients from database and write result back to database. |
C#, VB\WebProject1\SimpleController | Send a simple email from ASP.NET MVC by Form Post/Ajax Post. |
C#, VB\WebProject1\GmailOauthController | Send email using Gmail OAUTH/XOAUTH2. |
C#, VB\WebProject1\MassController | Send mass emails using background thread pool. |
C#, VB\WebProject1\DbRecipientsController | Send mass emails using background thread pool, select recipients from database and write result back to database. |
C#, VB\Simple | Send a simple email from .NET Windows Form. |
C#, VB\HtmlMail | Send text/html email using Web Browser Control Editor |
C#, VB\Mass | Send mass emails using thread pool. |
C#, VB\Oauth | Send email using Gmail/Office365/Hotmail OAUTH/XOAUTH2. |
C#, VB\Simple | Send text/plain or html email from Microsoft Store App (UAP). |
C#, VB\Mass | Send mass emails using thread pool from Microsoft Store App (UAP). |
C#, VB\GmailOauth | Send email using Gmail OAUTH/XOAUTH2. |
C#, VB\pocketpc.mobile | Send a simple email from .NET Compact Framework. |
VBScript, JScript\Simple | Send a simple email from ASP Classic. |
VBScript, JScript\SimpleQueue | Send email from ASP Classic to EASendMail Service. |
VBScript\GmailOauth | Send email using Gmail OAUTH/XOAUTH2. |
VBScript, JScript\AdvancedQueueWithDatabase | Send email from ASP Classic to EASendMail Service, background service will select recipients from database and write result back to database. |
Simple | Send a simple email from Delphi 7. |
HtmlMail | Send text/html email using Web Browser Control Editor |
Mass | Send mass emails using thread pool. |
Oauth | Send email using Gmail/Office365/Hotmail OAUTH/XOAUTH2. |
SQL | Send email from MS SQL Server stored procedure. |
VBScript/JScript/WScript | Send a simple email from VBScript/JScript/WScript. |
Simple | Send a simple email from VB 6.0. |
HtmlMail | Send text/html email using Web Browser Control Editor |
Mass | Send mass emails using thread pool. |
Oauth | Send email using Gmail/Office365/Hotmail OAUTH/XOAUTH2. |
Simple | Send a simple email from VC++. |
HtmlMail | Send text/html email using Web Browser Control Editor |
Mass | Send mass emails using thread pool. |
Oauth | Send email using Gmail/Office365/Hotmail OAUTH/XOAUTH2. |
Free Email Support
Not enough? Please contact our technical support team.
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 email account is recommended.
Appendix
Comments
If you have any comments or questions about above example codes, please click here to add your comments.