This tutorial introduces how to send email in Managed C++/CLI using SMTP. It also demonstrates SSL, S/MIME, Embedded Images, Email Queue and Multiple Threads usage.
Sections:
To better demonstrate how to send email using EASendMail, let’s create a Managed C++/CLI console project 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 2.0, 3.5, 4.0, 4.5, 4.6.1, 4.7.2, 4.8.1, .NET 5.0, .NET 6.0, .NET 7.0, .NET 8.0, .NET Standard 2.0 and .NET Compact Framework 2.0, 3.5.
File | .NET Framework Version |
Lib\[net20|40|45|461|472|481]\EASendMail.dll |
Built with .NET Framework 2.0, 4.0, 4.5, 4.6.1, 4.7.2, 4.8.1
It requires .NET Framework 2.0, 3.5 or later version. |
Lib\[net5.0|6.0|7.0|8.0]\EASendMail.dll |
Built with .NET 5.0, .NET 6.0, NET 7.0, NET 8.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|net35-cf]\EASendMail.dll |
Built with .NET Compact Framework 2.0, 3.5
It requires .NET Compact Framework 2.0, 3.5 or later version. |
Now add the following codes to the project and change From
, To
, Server
, User
and
Password
to corresponding value.
#include "stdafx.h"
using namespace System;
using namespace EASendMail;
int main(array<System::String ^> ^args)
{
try
{
SmtpMail ^oMail = gcnew 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 = gcnew AddressCollection("support@emailarchitect.net");
// Set email subject
oMail->Subject = "test email from Managed C++ project";
// Set email body
oMail->TextBody = "this is a test email sent from Managed C++ project, do not reply";
// Your SMTP server address
SmtpServer ^oServer = gcnew 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 from Managed C++...");
SmtpClient ^oSmtp = gcnew 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);
}
return 0;
}
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
[Managed C++/CLI Example - Email syntax]
To better understand the email address syntax, please refer to the following codes.
// 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 = gcnew MailAddress( "Tester", "test@adminsystem.com" );
oMail->From = gcnew MailAddress( "Tester<test@adminsystem.com>");
oMail=>From = gcnew 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 = gcnew AddressCollection( "test1@adminsystem.com, test2@adminsystem.com" );
oMail->To = gcnew AddressCollection( "Test1<test@adminsystem.com>, Test2<test2@adminsystem.com>");
// You can add more recipient by Add method
oMail->To->Add( gcnew MailAddress( "tester", "test@adminsystem.com"));
// You can also add carbon copy (CC) or blind carbon copy (BCC) in the email.
oMail->Cc->Add( gcnew MailAddress( "CC recipient", "cc@adminsystem.com"));
oMail->Bcc->Add( gcnew 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++/CLI - 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 = gcnew 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++/CLI - Using log file to detect SMTP server response - Example]
oSmtp->LogFileName = "d:\\smtp.txt";
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++/CLI 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 Managed C++/CLI project. In this section, I will introduce the SSL connection.
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
// Send email by normal TCP/IP without SSL connection
SmtpServer^ oServer = gcnew SmtpServer("localhost 25");
oServer->ConnectType = SmtpConnectType::ConnectNormal;
// Send email by SSL connection with STARTTLS command switching
SmtpServer^ oServer = gcnew SmtpServer("localhost 25");
oServer->ConnectType = SmtpConnectType::ConnectSTARTTLS;
// Send email by SSL connection with direct SSL.
SmtpServer^ oServer = gcnew 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 = gcnew SmtpServer("localhost 465");
oServer->ConnectType = SmtpConnectType::ConnectSSLAuto
SmtpServer^ oServer = gcnew SmtpServer("localhost 25");
oServer->ConnectType = SmtpConnectType::ConnectSSLAuto;
// If server supports SSL/TLS, then SSL/TLS is used, otherwise normal TCP is used.
SmtpServer^ oServer = gcnew SmtpServer("localhost 25");
oServer->ConnectType = SmtpConnectType::ConnectTryTLS;
SmtpServer^ oServer = gcnew SmtpServer("localhost 587");
oServer->ConnectType = SmtpConnectType::ConnectTryTLS;
Note
Remarks: All of samples in this section are based on first section: A simple Managed C++/CLI 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 direct SSL connection on 465 port.
Note
To get the full sample projects, please refer to Samples section.
#include "stdafx.h"
using namespace System;
using namespace EASendMail;
int main(array<System::String ^> ^args)
{
try
{
SmtpMail ^oMail = gcnew 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 = gcnew AddressCollection("support@emailarchitect.net");
// Set email subject
oMail->Subject = "test email from Managed C++ project";
// Set email body
oMail->TextBody = "this is a test email sent from Managed C++ project, do not reply";
// Your SMTP server address
SmtpServer ^oServer = gcnew 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 from Managed C++...");
SmtpClient ^oSmtp = gcnew 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);
}
return 0;
}
The following example codes demonstrate how to use EASendMail SMTP component to send email with TLS (STARTTLS command) connection on 25 port.
Note
To get the full sample projects, please refer to Samples section.
#include "stdafx.h"
using namespace System;
using namespace EASendMail;
int main(array<System::String ^> ^args)
{
try
{
SmtpMail ^oMail = gcnew 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 = gcnew AddressCollection("support@emailarchitect.net");
// Set email subject
oMail->Subject = "test email from Managed C++ project";
// Set email body
oMail->TextBody = "this is a test email sent from Managed C++ project, do not reply";
// Your SMTP server address
SmtpServer ^oServer = gcnew SmtpServer("smtp.emailarchitect.net");
// User and password for ESMTP authentication
oServer->User = "test@emailarchitect.net";
oServer->Password = "testpassword";
// Set 25 port or 587 port
oServer->Port = 25;
// detect TLS/SSL automatically, you can also use ConnectSSLAuto
oServer->ConnectType = SmtpConnectType::ConnectSTARTTLS;
Console::WriteLine("start to send email from Managed C++...");
SmtpClient ^oSmtp = gcnew 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);
}
return 0;
}
Next Section
At next section I will introduce how to send email using Gmail account.
In previous section, I introduced how to send email over SSL connection. In this section, I will introduce how to use your Gmail account to send email in Managed 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.
Last update: Google has disabled App password, you have to switch to Gmail SMTP OAUTH. If you don’t want to change your code, you can have a try with EA Oauth Service.
Note
Remarks: All of samples in this section are based on first section: A simple Managed C++/CLI 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.
Note
To get the full sample projects, please refer to Samples section.
#include "stdafx.h"
using namespace System;
using namespace EASendMail;
int main(array<System::String ^> ^args)
{
try
{
SmtpMail ^oMail = gcnew SmtpMail("TryIt");
// Your Gmail email address
oMail->From = "gmailid@gmail.com";
// Set recipient email address, please change it to yours
oMail->To = gcnew AddressCollection("support@emailarchitect.net");
// Set email subject
oMail->Subject = "test email from Managed C++ with Gmail account";
// Set email body
oMail->TextBody = "this is a test email sent from Managed C++ project with gmail";
// Gmail SMTP server address
SmtpServer ^oServer = gcnew SmtpServer("smtp.gmail.com");
// Gmail user authentication
// For example: your email is "gmailid@gmail.com", then the user should be "gmailid@gmail.com"
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";
// Use 465 port
oServer->Port = 465;
// detect SSL/TLS automatically
oServer->ConnectType = SmtpConnectType::ConnectSSLAuto;
Console::WriteLine("start to send email with SSL connection...");
SmtpClient ^oSmtp = gcnew 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);
}
return 0;
}
The following example codes demonstrate how to use EASendMail SMTP component to send email using Gmail account.
Note
To get the full sample projects, please refer to Samples section.
#include "stdafx.h"
using namespace System;
using namespace EASendMail;
int main(array<System::String ^> ^args)
{
try
{
SmtpMail ^oMail = gcnew SmtpMail("TryIt");
// Your Gmail email address
oMail->From = "gmailid@gmail.com";
// Set recipient email address, please change it to yours
oMail->To = gcnew AddressCollection("support@emailarchitect.net");
// Set email subject
oMail->Subject = "test email from Managed C++ with Gmail account";
// Set email body
oMail->TextBody = "this is a test email sent from Managed C++ project with gmail";
// Gmail SMTP server address
SmtpServer ^oServer = gcnew SmtpServer("smtp.gmail.com");
// Gmail user authentication
// For example: your email is "gmailid@gmail.com", then the user should be "gmailid@gmail.com"
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";
// Use 587 port
oServer->Port = 587;
// detect SSL/TLS automatically
oServer->ConnectType = SmtpConnectType::ConnectSSLAuto;
Console::WriteLine("start to send email with SSL connection...");
SmtpClient ^oSmtp = gcnew 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);
}
return 0;
}
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 with Yahoo account.
In previous section, I introduced how to send email using Gmail account. In this section, I will introduce how to use your Yahoo account to send email in Managed 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 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: A simple Managed C++/CLI 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.
Note
To get the full sample projects, please refer to Samples section.
#include "stdafx.h"
using namespace System;
using namespace EASendMail;
int main(array<System::String ^> ^args)
{
try
{
SmtpMail ^oMail = gcnew SmtpMail("TryIt");
// Your Yahoo email address
oMail->From = "myid@yahoo.com";
// Set recipient email address, please change it to yours
oMail->To = gcnew AddressCollection("support@emailarchitect.net");
// Set email subject
oMail->Subject = "test email from Managed C++ with Yahoo account";
// Set email body
oMail->TextBody = "this is a test email sent from Managed C++ project with yahoo";
// Yahoo SMTP server address
SmtpServer ^oServer = gcnew 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 direct SSL connection.
// So we should change the port to 465.
oServer->Port = 465;
// detect SSL/TLS automatically
oServer->ConnectType = SmtpConnectType::ConnectSSLAuto;
Console::WriteLine("start to send email with SSL connection...");
SmtpClient ^oSmtp = gcnew 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);
}
return 0;
}
The following example codes demonstrate how to send email using Yahoo account over TLS on 587 port.
Note
To get the full sample projects, please refer to Samples section.
#include "stdafx.h"
using namespace System;
using namespace EASendMail;
int main(array<System::String ^> ^args)
{
try
{
SmtpMail ^oMail = gcnew SmtpMail("TryIt");
// Your Yahoo email address
oMail->From = "myid@yahoo.com";
// Set recipient email address, please change it to yours
oMail->To = gcnew AddressCollection("support@emailarchitect.net");
// Set email subject
oMail->Subject = "test email from Managed C++ with Yahoo account";
// Set email body
oMail->TextBody = "this is a test email sent from Managed C++ project with yahoo";
// Yahoo SMTP server address
SmtpServer ^oServer = gcnew 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 587 port
oServer->Port = 587;
// detect SSL/TLS automatically
oServer->ConnectType = SmtpConnectType::ConnectSSLAuto;
Console::WriteLine("start to send email with SSL connection...");
SmtpClient ^oSmtp = gcnew 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);
}
return 0;
}
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/MSN Live account.
In previous section, I introduced how to send email using Yahoo account. In this section, I will introduce how to use your Hotmail/MSN Live/Outlook.com/Office365 account to send email in Managed 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: A simple Managed C++/CLI 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/MSN Live account.
Note
To get the full sample projects, please refer to Samples section.
#include "stdafx.h"
using namespace System;
using namespace EASendMail;
int main(array<System::String ^> ^args)
{
try
{
SmtpMail ^oMail = gcnew SmtpMail("TryIt");
// Your Hotmail email address
oMail->From = "liveid@hotmail.com";
// Set recipient email address, please change it to yours
oMail->To = gcnew AddressCollection("support@emailarchitect.net");
// Set email subject
oMail->Subject = "test email from Managed C++ with Hotmail account";
// Set email body
oMail->TextBody = "this is a test email sent from Managed C++ project with Hotmail";
// Hotmail SMTP server address
SmtpServer ^oServer = gcnew 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
oServer->Port = 587;
// detect SSL/TLS automatically
oServer->ConnectType = SmtpConnectType::ConnectSSLAuto;
Console::WriteLine("start to send email with SSL connection...");
SmtpClient ^oSmtp = gcnew 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);
}
return 0;
}
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.
Last update: Microsoft has disabled App password, you have to switch to Hotmail SMTP OAUTH and Office365 SMTP/EWS/Ms Graph API OAUTH. If you don’t want to change your code, you can have a try with EA Oauth Service.
[C++/CLI - Send Email using Office 365 over Explicit SSL (TLS) on 587 Port - Example]
The following example codes demonstrate how to send email using Office 365 in C++/CLI over TLS 587 port.
Note
To get the full sample projects, please refer to Samples section.
#include "stdafx.h"
using namespace System;
using namespace EASendMail;
int main(array<System::String ^> ^args)
{
try
{
SmtpMail ^oMail = gcnew SmtpMail("TryIt");
// Your office365 email address
oMail->From = "yourid@yourdomain";
// Set recipient email address, please change it to yours
oMail->To = gcnew AddressCollection("support@emailarchitect.net");
// Set email subject
oMail->Subject = "test email from Managed C++ with office365 account";
// Set email body
oMail->TextBody = "this is a test email sent from Managed C++ project with office365";
// Office365 SMTP server address
SmtpServer ^oServer = gcnew SmtpServer("smtp.office365.com");
// office365 user authentication should use your
// email address as the user name.
oServer->User = "yourid@yourdomain";
// 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";
// Use 587 port
oServer->Port = 587;
// detect SSL/TLS automatically
oServer->ConnectType = SmtpConnectType::ConnectSSLAuto;
Console::WriteLine("start to send email with SSL connection...");
SmtpClient ^oSmtp = gcnew 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);
}
return 0;
}
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.
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 without specified SMTP server.
In previous section, I introduced how to send email using Hotmail/MSN Live account. In this section, I will introduce how to use DNS lookup to send email without specified SMTP server in Managed C++.
Sections:
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: A simple Managed C++/CLI 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.
Note
To get the full sample projects, please refer to Samples section.
#include "stdafx.h"
using namespace System;
using namespace EASendMail;
int main(array<System::String ^> ^args)
{
try
{
SmtpMail ^oMail = gcnew 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 = gcnew AddressCollection("support@emailarchitect.net");
// Set email subject
oMail->Subject = "direct send email from Managed C++ project";
// Set email body
oMail->TextBody = "this is a test email sent from Managed C++ project directly";
// Set smtp server address to ""
SmtpServer ^oServer = gcnew SmtpServer("");
// Do not set user authentication
// Do not set SSL/TLS
Console::WriteLine("start to send email directly...");
SmtpClient ^oSmtp = gcnew 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);
}
return 0;
}
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 compose HTML email.
In previous section, I introduced how to send email without specified SMTP server. In this section, I will introduce how to compose and send HTML email in Managed 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: A simple Managed C++/CLI 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.
Note
To get the full sample projects, please refer to Samples section.
#include "stdafx.h"
using namespace System;
using namespace EASendMail;
int main(array<System::String ^> ^args)
{
try
{
SmtpMail ^oMail = gcnew 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 = gcnew AddressCollection("support@emailarchitect.net");
// Set email subject
oMail->Subject = "test HTML email from Managed C++ project";
// Set HTML email body
oMail->HtmlBody = "<font size=5>This is</font> <font color=red><b>a test</b></font>";
// Your SMTP server address
SmtpServer ^oServer = gcnew 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 = gcnew 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);
}
return 0;
}
After you received the email by your email client, the body text is like this:
Of course, you don’t have to write the HTML source body text in your application manually. You can build a html file with HTML tools and use ImportHtmlBody method to import the html file directly.
You can also refer to the htmlmail.* samples in EASendMail Installer. Those samples demonstrate how to build a HTML email editor and send HTML email with attachment or embedded images/pictures.
Next Section
At next section I will introduce how to attach file attachment to email message.
In previous section, I introduced how to send HTML email. In this section, I will introduce how to add attachment to email in Managed 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: A simple Managed C++/CLI 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 file attachments.
Note
To get the full sample projects, please refer to Samples section.
#include "stdafx.h"
using namespace System;
using namespace EASendMail;
int main(array<System::String ^> ^args)
{
try
{
SmtpMail ^oMail = gcnew 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 = gcnew AddressCollection("support@emailarchitect.net");
// Set email subject
oMail->Subject = "test HTML email from Managed C++ 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 = gcnew 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 = gcnew 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);
}
return 0;
}
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 file attachment. In this section, I will introduce how to add embedded images to email in Managed C++.
To attach an embedded images to email, you should add an attachment to email at
first. Then you should assign an unique identifier(contentid) to this attachment.
Finally, you need to replace the <img src="your file name" />
to <img src="cid:yourcontentid"
/>
.
Note
Remarks: All of samples in this section are based on first section: A simple Managed C++/CLI 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.
Note
To get the full sample projects, please refer to Samples section.
#include "stdafx.h"
using namespace System;
using namespace EASendMail;
int main(array<System::String ^> ^args)
{
try
{
SmtpMail ^oMail = gcnew 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 = gcnew AddressCollection("support@emailarchitect.net");
// Set email subject
oMail->Subject = "test HTML email from Managed C++ with inline attachment";
// Set HTML body
oMail->HtmlBody = "<font size=5>This is</font> <font color=red><b>a test</b></font>";
// 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 picture.</body></html>";
// Your SMTP server address
SmtpServer ^oServer = gcnew 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 inline image...");
SmtpClient ^oSmtp = gcnew 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);
}
return 0;
}
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.
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 previous section, I introduced how to send email with embedded images. In this section, I will introduce how to sign email with digital certificate in Managed 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: A simple Managed C++/CLI 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 sign email with digital certificate.
Note
To get the full sample projects, please refer to Samples section.
#include "stdafx.h"
using namespace System;
using namespace System::Security::Cryptography::X509Certificates;
using namespace EASendMail;
X509Certificate2^ _findCertificate(String ^storeName, String ^emailAddress)
{
X509Certificate2 ^cert = nullptr;
X509Store ^store = gcnew 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;
}
int main(array<System::String ^> ^args)
{
try
{
SmtpMail ^oMail = gcnew 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 = gcnew AddressCollection("support@emailarchitect.net");
// Set email subject
oMail->Subject = "test email from Managed C++ project with digital signature";
// Set email body
oMail->TextBody = "this is a test email sent from Managed C++ project with digital signature";
X509Certificate2 ^signerCertificate = _findCertificate("My", oMail->From->Address);
if (signerCertificate == nullptr)
throw gcnew Exception("No signer certificate found!");
oMail->From->Certificate2 = signerCertificate;
// You can also load the signer certificate from a pfx file.
/* String ^pfxPath = "D:\\TestCerts\\signer.pfx";
X509Certificate2 ^signerCertFromPfx = gcnew 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 = gcnew 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 = gcnew 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);
}
return 0;
}
You can use SmtpMail.SignatureHashAlgorithm property to set MD5, SHA1, SHA256, SHA384 or SHA512 signature algorithm. SHA256 is recommended.
RSASSA-PSS Signature in 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 Managed 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: A simple Managed C++/CLI 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.
Note
To get the full sample projects, please refer to Samples section.
#include "stdafx.h"
using namespace System;
using namespace System::Security::Cryptography::X509Certificates;
using namespace EASendMail;
X509Certificate2^ _findCertificate(String ^storeName, String ^emailAddress)
{
X509Certificate2 ^cert = nullptr;
X509Store ^store = gcnew 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;
}
int main(array<System::String ^> ^args)
{
try
{
SmtpMail ^oMail = gcnew 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 = gcnew AddressCollection("support@emailarchitect.net");
// Set email subject
oMail->Subject = "test encrypted email from Managed C++ project";
// Set email body
oMail->TextBody = "this is a test encrypted email sent from Managed C++";
X509Certificate2 ^signerCertificate = _findCertificate("My", oMail->From->Address);
if (signerCertificate == nullptr)
throw gcnew Exception("No signer certificate found!");
oMail->From->Certificate2 = signerCertificate;
// You can also load the signer certificate from a pfx file.
/* String ^pfxPath = "D:\\TestCerts\\signer.pfx";
X509Certificate2 ^signerCertFromPfx = gcnew 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 = dynamic_cast<MailAddress^>(oMail->To[i]);
X509Certificate2 ^encryptCert = _findCertificate("AddressBook", oAddress->Address);
if (encryptCert == nullptr)
encryptCert = _findCertificate("My", oAddress->Address);
if (encryptCert == nullptr)
throw gcnew Exception("No encryption certificate found!");
oAddress->Certificate2 = encryptCert;
// You can also load the encryptor certificate from a cer file like this
/*
String ^cerPath = "D:\\TestCerts\\encryptor.cer";
X509Certificate2 ^encryptCertFromFile = gcnew X509Certificate2(cerPath);
oAddress->Certificate2 = encryptCertFromFile;
*/
}
// Your SMTP server address
SmtpServer ^oServer = gcnew 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 encrypted email ...");
SmtpClient ^oSmtp = gcnew 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);
}
return 0;
}
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 Managed 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: A simple Managed C++/CLI 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.
Note
To get the full sample projects, please refer to Samples section.
#include "stdafx.h"
using namespace System;
using namespace EASendMail;
//EASendMail EventHandler
System::Void OnIdle( System::Object ^sender, System::Boolean % 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();
}
System::Void OnConnected(System::Object ^sender, System::Boolean % cancel )
{
Console::WriteLine("Connected");
}
System::Void OnSendingDataStream(System::Object ^sender, int sent,
int total, System::Boolean % cancel )
{
Console::WriteLine( String::Format( "{0}/{1} sent", sent, total));
}
System::Void OnAuthorized( System::Object ^sender, System::Boolean % cancel )
{
Console::WriteLine("Authorized");
}
System::Void OnSecuring( System::Object ^sender, System::Boolean % cancel )
{
Console::WriteLine("Securing ...");
}
int main(array<System::String ^> ^args)
{
try
{
SmtpMail ^oMail = gcnew 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 = gcnew AddressCollection("support@emailarchitect.net");
// Set email subject
oMail->Subject = "test email from Managed C++ project";
// Set email body
oMail->TextBody = "this is a test email sent from Managed C++ project, do not reply";
// Your SMTP server address
SmtpServer ^oServer = gcnew 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 event handler ...");
SmtpClient ^oSmtp = gcnew SmtpClient();
// Catching the following events is not necessary,
// just make the application more user friendly.
// If you use the object in asp.net/windows service or non-gui application,
// You need not to catch the following events.
oSmtp->OnIdle += gcnew SmtpClient::OnIdleEventHandler(&OnIdle);
oSmtp->OnAuthorized += gcnew SmtpClient::OnAuthorizedEventHandler(&OnAuthorized);
oSmtp->OnConnected += gcnew SmtpClient::OnConnectedEventHandler(&OnConnected);
oSmtp->OnSecuring += gcnew SmtpClient::OnSecuringEventHandler(&OnSecuring);
oSmtp->OnSendingDataStream +=
gcnew 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);
}
return 0;
}
Next Section
At next section I will introduce how to send email in asynchronous mode.
In previous section, I introduced how to use event handler to monitor the progress. In this section, I will introduce how to send email in asynchronous mode in Managed C++.
In synchronous mode, once SendMail method is called, it returns to application after the method is complete. Therefore, if the runtime (it depends on the networking connection and the email size) is long, your application cannot do anything before this method ends, which results “my application is blocked or halted”. In contrast, in asynchronous mode, as BeginSendMail method works in background, this methods return to application immediately no matter the running method is complete or not.
Note
Remarks: All of samples in this section are based on first section: A simple Managed C++/CLI 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 asynchronous mode.
Note
To get the full sample projects, please refer to Samples section.
#include "stdafx.h"
using namespace System;
using namespace EASendMail;
int main(array<System::String ^> ^args)
{
try
{
SmtpMail ^oMail = gcnew 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 = gcnew AddressCollection("support@emailarchitect.net");
// Set email subject
oMail->Subject = "test email from Managed C++ project with asynchronous mode";
// Set email body
oMail->TextBody = "this is a test email sent from Managed C++ project asynchronously";
// Your SMTP server address
SmtpServer ^oServer = gcnew 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 = gcnew SmtpClient();
SmtpClientAsyncResult ^oResult = oSmtp->BeginSendMail(
oServer, oMail, nullptr, nullptr);
// Wati for the email sending...
while (!oResult->IsCompleted)
{
Console::WriteLine("waiting..., you can do other thing!");
oResult->AsyncWaitHandle->WaitOne(50, false);
}
oSmtp->EndSendMail(oResult);
Console::WriteLine("email was sent successfully!");
}
catch (Exception ^ep)
{
Console::WriteLine("failed to send email with the following error:");
Console::WriteLine(ep->Message);
}
return 0;
}
Next Section
At next section I will introduce how to send mass email with multiple threads.
In previous section, I introduced how to use asynchronous mode. In this section, I will introduce how to send mass email with multiple threads in Managed 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: A simple Managed C++/CLI 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.
Note
To get the full sample projects, please refer to Samples section.
#include "stdafx.h"
using namespace System;
using namespace EASendMail;
int main(array<System::String ^> ^args)
{
array<String^> ^arRcpt = {"test1@adminsystem.com",
"test2@adminsystem.com",
"test3@adminsystem.com" };
int nRcpt = arRcpt->Length;
array<SmtpMail^> ^arMail = gcnew array<SmtpMail^>(nRcpt);
array<SmtpClient^> ^arSmtp = gcnew array<SmtpClient^>(nRcpt);
array<SmtpClientAsyncResult^> ^arResult = gcnew array<SmtpClientAsyncResult^>(nRcpt);
for (int i = 0; i < nRcpt; i++)
{
arMail[i] = gcnew SmtpMail("TryIt");
arSmtp[i] = gcnew 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 Managed C++";
// Set email body
oMail->TextBody = "test from Managed C++, this email is sent to " + arRcpt[i];
// Your SMTP server address
SmtpServer ^oServer = gcnew 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, nullptr, nullptr );
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] == nullptr)
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] = nullptr;
nSent++;
}
}
return 0;
}
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
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\Oauth | Send email using Gmail and Office 365 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\OauthController | Send email using Gmail and Office 365 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\HtmlMailWebView2 | Send text/html email using WebView2 Control Editor |
C#, VB\Mass | Send mass emails using thread pool. |
C#, VB\Oauth | Send email using Gmail and Office365/Hotmail 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\Oauth | Send email using Gmail and Office 365 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.