email component

EASendMail SMTP Component > Using EASendMail in Visual C++ to send email

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

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

Introduction

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

Installation

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

A simple email sending project

First of all, let's create a Visual C++ Win32 console project at first.

Visual C++ console email sample

Add Reference of EASendMail ActiveX Object to Visual C++ Project

To use EASendMail SMTP ActiveX Object in your C++ project, the first step is "Add header files of EASendMail to your project". Please go to "C:\Program Files\EASendMail\Samples_VC\simple.vcNative" or "C:\Program Files (x86)\EASendMail\Samples_VC\simple.vcNative" folder, find "easendmailobj.tlh" and "easendmailobj.tli", and then copy these files to your project folder.

Visual C++ email reference

Now add the following code in your Visual C++ project like this:

/*[Visual C++ Example Code - Send Simple Email]*/
#include "stdafx.h"

#include "easendmailobj.tlh"
using namespace EASendMailObjLib;

int _tmain(int argc, _TCHAR* argv[])
{
    ::CoInitialize( NULL );

    IMailPtr oSmtp = NULL;
    oSmtp.CreateInstance( "EASendMailObj.Mail");
    oSmtp->LicenseCode = _T("TryIt");
    
    //Set your sender email address
    oSmtp->FromAddr = _T("test@emailarchitect.net");
    //Add recipient email address
    oSmtp->AddRecipientEx( _T("support@emailarchitect.net"), 0 );
    //Set email subject
    oSmtp->Subject = _T("simple email from Visual C++ project");
    //Set email body
    oSmtp->BodyText = _T("this is a test email sent from Visual C++ project, do not reply");
    
    //Your smtp server address
    oSmtp->ServerAddr = _T("smtp.emailarchitect.net");
    //User and password for ESMTP authentication, if your server doesn't 
    //require User authentication, please remove the following codes.
    oSmtp->UserName = _T("test@emailarchitect.net");
    oSmtp->Password = _T("testpassword");

    //If your smtp server requires SSL connection, please add this line
    //oSmtp->SSL_init();

    _tprintf(_T("Start to send email ...\r\n" ));
  
    if( oSmtp->SendMail() == 0 )
    {
        _tprintf( _T("email was sent successfully!\r\n"));
    }
    else
    {
        _tprintf( _T("failed to send email with the following error: %s\r\n"),
            (const TCHAR*)oSmtp->GetLastErrDescription());
    }

    if( oSmtp != NULL )
        oSmtp.Release();

    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.

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

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

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

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

Visual C++ console email sample

Email Address Syntax and Multiple Recipients

Mail Address Syntax in EASendMail SMTP Component:

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

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

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

/*[Visual C++ Example Code - Email syntax]*/
oSmtp->FromAddr = _T("Tester<test@adminsystem.com>");
oSmtp->FromAddr = _T("test@adminsystem.com");
oSmtp->FromAddr = _T("<test@adminsystem.com>");

// Using AddRecipientEx to add To, Cc and Bcc in Visual C++
// Multiple addresses are separated with (,)
// The syntax is like this: "test@adminsystem.com, test1@adminsystem.com"
oSmtp->AddRecipientEx(_T("test1@adminsystem.com, test2@adminsystem.com"), 0);
oSmtp->AddRecipientEx(_T("Test1<test@adminsystem.com>, Test2<test2@adminsystem.com>"), 0);

// You can also add carbon copy (CC) or blind carbon copy (BCC) in the email.
oSmtp->AddRecipientEx(_T("CC recipient<cc@adminsystem.com>"), 1);
oSmtp->AddRecipientEx(_T("Bcc recipient<bcc@adminsystem.com>"), 2);

Send email over SSL Connection

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

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

Send email by Gmail account with SSL connection

/*[Visual C++ Example Code - Send Email by Gmail Account with SSL connection]*/
#include "stdafx.h"

#include "easendmailobj.tlh"
using namespace EASendMailObjLib;

int _tmain(int argc, _TCHAR* argv[])
{
    ::CoInitialize( NULL );

    IMailPtr oSmtp = NULL;
    oSmtp.CreateInstance( "EASendMailObj.Mail");
    oSmtp->LicenseCode = _T("TryIt");
    
    //Set your gmail email address
    oSmtp->FromAddr = _T("gmailid@gmail.com");
    //Add recipient email address
    oSmtp->AddRecipientEx( _T("support@emailarchitect.net"), 0 );
    //Set email subject
    oSmtp->Subject = _T("simple email from Visual C++ with gmail account");
    //Set email body
    oSmtp->BodyText = _T("this is a test email sent from Visual C++ project with Gmail");
    
    //Gmail smtp server address
    oSmtp->ServerAddr = _T("smtp.gmail.com");
    //gmail user authentication should use your 
    //gmail email address as the user name. 
    oSmtp->UserName = _T("gmailid@gmail.com");
    oSmtp->Password = _T("yourpassword");

    //Send email over SSL/TLS connection.
    oSmtp->SSL_init();

    _tprintf(_T("Start to send email via gmail account ...\r\n" ));
  
    if( oSmtp->SendMail() == 0 )
    {
        _tprintf( _T("email was sent successfully!\r\n"));
    }
    else
    {
        _tprintf( _T("failed to send email with the following error: %s\r\n"),
            (const TCHAR*)oSmtp->GetLastErrDescription());
    }

    if( oSmtp != NULL )
        oSmtp.Release();

    return 0;
}

Send email by Yahoo account with SSL connection

/*[Visual C++ Example Code - Send Email by Yahoo Account with SSL connection]*/
#include "stdafx.h"

#include "easendmailobj.tlh"
using namespace EASendMailObjLib;

int _tmain(int argc, _TCHAR* argv[])
{
    ::CoInitialize( NULL );

    IMailPtr oSmtp = NULL;
    oSmtp.CreateInstance( "EASendMailObj.Mail");
    oSmtp->LicenseCode = _T("TryIt");
    
    //Set your Yahoo email address
    oSmtp->FromAddr = _T("myid@yahoo.com");
    //Add recipient email address
    oSmtp->AddRecipientEx( _T("support@emailarchitect.net"), 0 );
    //Set email subject
    oSmtp->Subject = _T("simple email from Visual C++ with Yahoo account");
    //Set email body
    oSmtp->BodyText = _T("this is a test email sent from Visual C++ project with Yahoo");
    
    //Yahoo smtp server address
    oSmtp->ServerAddr = _T("smtp.mail.yahoo.com");
    //Yahoo user authentication should use your 
    //Yahoo email address as the user name. 
    oSmtp->UserName = _T("myid@yahoo.com");
    oSmtp->Password = _T("yourpassword");

    'Because yahoo deploys SMTP server on 465 port with direct SSL connection.
    'So we should change the port to 465.
    oSmtp->ServerPort = 465;

    //Send email over SSL/TLS connection.
    oSmtp->SSL_init();

    _tprintf(_T("Start to send email via Yahoo account ...\r\n" ));
  
    if( oSmtp->SendMail() == 0 )
    {
        _tprintf( _T("email was sent successfully!\r\n"));
    }
    else
    {
        _tprintf( _T("failed to send email with the following error: %s\r\n"),
            (const TCHAR*)oSmtp->GetLastErrDescription());
    }

    if( oSmtp != NULL )
        oSmtp.Release();

    return 0;
}

Send email by MSN/hotmail account with SSL connection

/*[Visual C++ Example Code - Send Email by MSN/Hotmail Account with SSL connection]*/
#include "stdafx.h"

#include "easendmailobj.tlh"
using namespace EASendMailObjLib;

int _tmain(int argc, _TCHAR* argv[])
{
    ::CoInitialize( NULL );

    IMailPtr oSmtp = NULL;
    oSmtp.CreateInstance( "EASendMailObj.Mail");
    oSmtp->LicenseCode = _T("TryIt");
    
    //Set your hotmail email address
    oSmtp->FromAddr = _T("liveid@hotmail.com");
    //Add recipient email address
    oSmtp->AddRecipientEx( _T("support@emailarchitect.net"), 0 );
    //Set email subject
    oSmtp->Subject = _T("simple email from Visual C++ with hotmail account");
    //Set email body
    oSmtp->BodyText = _T("this is a test email sent from Visual C++ project with hotmail");
    
    //Hotmail smtp server address
    oSmtp->ServerAddr = _T("smtp.live.com");
    //Hotmail user authentication should use your 
    //Hotmail email address as the user name. 
    oSmtp->UserName = _T("liveid@hotmail.com");
    oSmtp->Password = _T("yourpassword");

    //Send email over SSL/TLS connection.
    oSmtp->SSL_init();

    _tprintf(_T("Start to send email via Hotmail account ...\r\n" ));
  
    if( oSmtp->SendMail() == 0 )
    {
        _tprintf( _T("email was sent successfully!\r\n"));
    }
    else
    {
        _tprintf( _T("failed to send email with the following error: %s\r\n"),
            (const TCHAR*)oSmtp->GetLastErrDescription());
    }

    if( oSmtp != NULL )
        oSmtp.Release();

    return 0;
}

Reply-To, Return-Path and Mail Priority

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

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

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

Send email directly without SMTP server(MX DNS lookup)

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

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

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

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

/*[Visual C++ Example Code - Send Email Directly without SMTP Server]*/
#include "stdafx.h"

#include "easendmailobj.tlh"
using namespace EASendMailObjLib;

int _tmain(int argc, _TCHAR* argv[])
{
    ::CoInitialize( NULL );

    IMailPtr oSmtp = NULL;
    oSmtp.CreateInstance( "EASendMailObj.Mail");
    oSmtp->LicenseCode = _T("TryIt");
    
    //Set your sender email address
    oSmtp->FromAddr = _T("test@emailarchitect.net");
    //Add recipient email address
    oSmtp->AddRecipientEx( _T("support@emailarchitect.net"), 0 );
    //Set email subject
    oSmtp->Subject = _T("direct email from Visual C++ project");
    //Set email body
    oSmtp->BodyText = _T("this is a test email sent from Visual C++ project directly");
    
    //Set smtp server address to ""
    oSmtp->ServerAddr = _T("");
   
    //Do not set user authentication
    //Do not set SSL connection

    _tprintf(_T("Start to send email directly ...\r\n" ));
  
    if( oSmtp->SendMail() == 0 )
    {
        _tprintf( _T("email was sent successfully!\r\n"));
    }
    else
    {
        _tprintf( _T("failed to send email with the following error: %s\r\n"),
            (const TCHAR*)oSmtp->GetLastErrDescription());
    }

    if( oSmtp != NULL )
        oSmtp.Release();

    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.

Send email with Html body

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

/*[Visual C++ Example Code - Send HTML Email]*/
#include "stdafx.h"

#include "easendmailobj.tlh"
using namespace EASendMailObjLib;

int _tmain(int argc, _TCHAR* argv[])
{
    ::CoInitialize( NULL );

    IMailPtr oSmtp = NULL;
    oSmtp.CreateInstance( "EASendMailObj.Mail");
    oSmtp->LicenseCode = _T("TryIt");
    
    //Set your sender email address
    oSmtp->FromAddr = _T("test@emailarchitect.net");
    //Add recipient email address
    oSmtp->AddRecipientEx( _T("support@emailarchitect.net"), 0 );
    //Set email subject
    oSmtp->Subject = _T("HTML email from Visual C++ project");
   
    //Set HTML body format
    oSmtp->BodyFormat = 1;
    
    //Set HTML email body
    oSmtp->BodyText = _T("<font size=5>This is</font> <font color=red><b>a test</b></font>");

    //Your smtp server address
    oSmtp->ServerAddr = _T("smtp.emailarchitect.net");
    //User and password for ESMTP authentication, if your server doesn't 
    //require User authentication, please remove the following codes.
    oSmtp->UserName = _T("test@emailarchitect.net");
    oSmtp->Password = _T("testpassword");

    //If your smtp server requires SSL connection, please add this line
    //oSmtp->SSL_init();

    _tprintf(_T("Start to send HTML email ...\r\n" ));
  
    if( oSmtp->SendMail() == 0 )
    {
        _tprintf( _T("email was sent successfully!\r\n"));
    }
    else
    {
        _tprintf( _T("failed to send email with the following error: %s\r\n"),
            (const TCHAR*)oSmtp->GetLastErrDescription());
    }

    if( oSmtp != NULL )
        oSmtp.Release();

    return 0;
}

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

Visual C++ html email sample

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

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

Visual C++ html editor

Send email with Attachment

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

/*[Visual C++ Example - Send Email with File Attachment]*/
#include "stdafx.h"

#include "easendmailobj.tlh"
using namespace EASendMailObjLib;

int _tmain(int argc, _TCHAR* argv[])
{
    ::CoInitialize( NULL );

    IMailPtr oSmtp = NULL;
    oSmtp.CreateInstance( "EASendMailObj.Mail");
    oSmtp->LicenseCode = _T("TryIt");
    
    //Set your sender email address
    oSmtp->FromAddr = _T("test@emailarchitect.net");
    //Add recipient email address
    oSmtp->AddRecipientEx( _T("support@emailarchitect.net"), 0 );
    //Set email subject
    oSmtp->Subject = _T("HTML email from Visual C++ project with attachment");
   
    //Set HTML body format
    oSmtp->BodyFormat = 1;
    
    //Set HTML email body
    oSmtp->BodyText = _T("<font size=5>This is</font> <font color=red><b>a test</b></font>");

    //adds attachment from local disk
    if(oSmtp->AddAttachment( _T("c:\\test.doc")) != 0)
    {
        _tprintf( _T("Failed to add attachment with error: %s\r\n"),
             (const TCHAR*)oSmtp->GetLastErrDescription());
    }

    //adds attachment from remote website
    if(oSmtp->AddAttachment( "http://www.emailarchitect.net/webapp/img/logo.jpg" ) != 0 )
    {
        _tprintf( _T("Failed to add attachment with error: %s\r\n"),
             (const TCHAR*)oSmtp->GetLastErrDescription());
    }

    //Your smtp server address
    oSmtp->ServerAddr = _T("smtp.emailarchitect.net");
    //User and password for ESMTP authentication, if your server doesn't 
    //require User authentication, please remove the following codes.
    oSmtp->UserName = _T("test@emailarchitect.net");
    oSmtp->Password = _T("testpassword");

    //If your smtp server requires SSL connection, please add this line
    //oSmtp->SSL_init();

    _tprintf(_T("Start to send HTML email ...\r\n" ));
  
    if( oSmtp->SendMail() == 0 )
    {
        _tprintf( _T("email was sent successfully!\r\n"));
    }
    else
    {
        _tprintf( _T("failed to send email with the following error: %s\r\n"),
            (const TCHAR*)oSmtp->GetLastErrDescription());
    }

    if( oSmtp != NULL )
        oSmtp.Release();

    return 0;
}

Send email with Embedded Images/Pictures

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

/*[Visual C++ Example Code - Send Email with Embedded Images/Pictures]*/
#include "stdafx.h"

#include "easendmailobj.tlh"
using namespace EASendMailObjLib;

int _tmain(int argc, _TCHAR* argv[])
{
    ::CoInitialize( NULL );

    IMailPtr oSmtp = NULL;
    oSmtp.CreateInstance( "EASendMailObj.Mail");
    oSmtp->LicenseCode = _T("TryIt");
    
    //Set your sender email address
    oSmtp->FromAddr = _T("test@emailarchitect.net");
    //Add recipient email address
    oSmtp->AddRecipientEx( _T("support@emailarchitect.net"), 0 );
    //Set email subject
    oSmtp->Subject = _T("HTML email from Visual C++ project with inline image");
   

    //Add embedded image and return the unique identifier of the attachment
    _bstr_t cid = oSmtp->AddInline( _T("c:\\test.gif"));
    if( cid.length() == 0 )
    {
        _tprintf(_T("failed add embedded image with error: %s"), 
            (const TCHAR*)oSmtp->GetLastErrDescription());
    }
   
    //Set HTML body format
    oSmtp->BodyFormat = 1;
    
    //use the cid as link in the body text
    oSmtp->BodyText = _bstr_t("<html><body>Hello, this is a  embedded <img src=\"cid:") + cid  
           + _bstr_t("\" > picture.</body><html>");

    //Your smtp server address
    oSmtp->ServerAddr = _T("smtp.emailarchitect.net");
    //User and password for ESMTP authentication, if your server doesn't 
    //require User authentication, please remove the following codes.
    oSmtp->UserName = _T("test@emailarchitect.net");
    oSmtp->Password = _T("testpassword");

    //If your smtp server requires SSL connection, please add this line
    //oSmtp->SSL_init();

    _tprintf(_T("Start to send HTML email with embedded image ...\r\n" ));
  
    if( oSmtp->SendMail() == 0 )
    {
        _tprintf( _T("email was sent successfully!\r\n"));
    }
    else
    {
        _tprintf( _T("failed to send email with the following error: %s\r\n"),
            (const TCHAR*)oSmtp->GetLastErrDescription());
    }

    if( oSmtp != NULL )
        oSmtp.Release();

    return 0;
}

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

Send email with Digital Signature(S/MIME)

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

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

Visual C++ email ceritificate

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

/*[Visual C++ Example - Send Email with Digital Signature (S/MIME)]*/
#include "stdafx.h"

#include "easendmailobj.tlh"
using namespace EASendMailObjLib;

int _tmain(int argc, _TCHAR* argv[])
{
    ::CoInitialize( NULL );

    IMailPtr oSmtp = NULL;
    oSmtp.CreateInstance( "EASendMailObj.Mail");
    oSmtp->LicenseCode = _T("TryIt");
    
    //Set your sender email address
    oSmtp->FromAddr = _T("test@emailarchitect.net");
    //Add recipient email address
    oSmtp->AddRecipientEx( _T("support@emailarchitect.net"), 0 );
    //Set email subject
    oSmtp->Subject = _T("email from Visual C++ with digital signature(S/MIME)");
    //Set email body
    oSmtp->BodyText = _T("this is a test email sent from Visual C++ with digital signature");
    
    //Your smtp server address
    oSmtp->ServerAddr = _T("smtp.emailarchitect.net");
    //User and password for ESMTP authentication, if your server doesn't 
    //require User authentication, please remove the following codes.
    oSmtp->UserName = _T("test@emailarchitect.net");
    oSmtp->Password = _T("testpassword");

    //If your smtp server requires SSL connection, please add this line
    //oSmtp->SSL_init();

    //add signer digital signature
    if( oSmtp->SignerCert->FindSubject(_T("test@emailarchitect.net"), 
        CERT_SYSTEM_STORE_CURRENT_USER , _T("my")) == VARIANT_FALSE )
    {
        _tprintf(_T("Error with signer certificate; %s\r\n"), 
            (const TCHAR*)oSmtp->SignerCert->GetLastError());
        return 0;
    }

    if( oSmtp->SignerCert->HasPrivateKey == VARIANT_FALSE )
    {
        _tprintf(_T("certificate does not have a private key, it can not sign email.\r\n" )); 
        return 0;			
    }

    _tprintf(_T("Start to send email ...\r\n" ));
  
    if( oSmtp->SendMail() == 0 )
    {
        _tprintf( _T("email was sent successfully!\r\n"));
    }
    else
    {
        _tprintf( _T("failed to send email with the following error: %s\r\n"),
            (const TCHAR*)oSmtp->GetLastErrDescription());
    }

    if( oSmtp != NULL )
        oSmtp.Release();

    return 0;
}

Send email with Email Encryption(S/MIME)

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

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

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

/*[Visual C++ Example - Encrypt email with certificate (S/MIME)]*/
#include "stdafx.h"

#include "easendmailobj.tlh"
using namespace EASendMailObjLib;

int _tmain(int argc, _TCHAR* argv[])
{
    ::CoInitialize( NULL );

    IMailPtr oSmtp = NULL;
    oSmtp.CreateInstance( "EASendMailObj.Mail");
    oSmtp->LicenseCode = _T("TryIt");
    
    //Set your sender email address
    oSmtp->FromAddr = _T("test@emailarchitect.net");
    //Add recipient email address
    oSmtp->AddRecipientEx( _T("support@emailarchitect.net"), 0 );
    //Set email subject
    oSmtp->Subject = _T("Encrypted email from Visual C++ (S/MIME)");
    //Set email body
    oSmtp->BodyText = _T("this is a test encrypted email sent from Visual C++");
    
    //Your smtp server address
    oSmtp->ServerAddr = _T("smtp.emailarchitect.net");
    //User and password for ESMTP authentication, if your server doesn't 
    //require User authentication, please remove the following codes.
    oSmtp->UserName = _T("test@emailarchitect.net");
    oSmtp->Password = _T("testpassword");

    //If your smtp server requires SSL connection, please add this line
    //oSmtp->SSL_init();

    //add signer digital signature
    if( oSmtp->SignerCert->FindSubject(_T("test@emailarchitect.net"), 
        CERT_SYSTEM_STORE_CURRENT_USER , _T("my")) == VARIANT_FALSE )
    {
        _tprintf(_T("Error with signer certificate; %s\r\n"), 
            (const TCHAR*)oSmtp->SignerCert->GetLastError());
        return 0;
    }

    if( oSmtp->SignerCert->HasPrivateKey == VARIANT_FALSE )
    {
        _tprintf(_T("certificate does not have a private key, it can not sign email.\r\n" )); 
        return 0;			
    }

    //find the encrypting certificate for every recipients
    ICertificatePtr oCert = NULL;
    oCert.CreateInstance("EASendMailObj.Certificate");
    if( oCert->FindSubject(_T("support@emailarchitect.net"), 
            CERT_SYSTEM_STORE_CURRENT_USER, _T("AddressBook")) == VARIANT_FALSE )
    {
        if(oCert->FindSubject(_T("support@emailarchitect.net"), 
                CERT_SYSTEM_STORE_CURRENT_USER, _T("my")) == VARIANT_FALSE )
        {
            _tprintf( _T("Encrypting certificate not found; %s\r\n"), 
                    (const TCHAR*)oCert->GetLastError()); 
            oCert.Release();        
            return 0;
        }
    }

    //add encrypting certificate
    oSmtp->RecipientsCerts->Add( oCert );
    oCert.Release();
	
    _tprintf(_T("Start to send email ...\r\n" ));
  
    if( oSmtp->SendMail() == 0 )
    {
        _tprintf( _T("email was sent successfully!\r\n"));
    }
    else
    {
        _tprintf( _T("failed to send email with the following error: %s\r\n"),
            (const TCHAR*)oSmtp->GetLastErrDescription());
    }

    if( oSmtp != NULL )
        oSmtp.Release();

    return 0;
}

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

Visual C++ sign and encrypt email

Send email with Asynchronous Mode

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

Send email with Event Handler

After SendMail method is invoked, if you want to know the progress of the email sending, you should use Event Handler. Event handler only supports asynchronous mode.

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

/*[Visual C++ Example - Send Email with Asynchronous Mode + Event Handler]*/
#include "stdafx.h"
#include <atlbase.h>
#include <atlcom.h>

#include "easendmailobj.tlh"
using namespace EASendMailObjLib;

#define IDC_SRCIMAIL 1

static _ATL_FUNC_INFO OnClosed = {CC_STDCALL, VT_EMPTY, 0};
static _ATL_FUNC_INFO OnSending = {CC_STDCALL, VT_EMPTY, 2, {VT_I4, VT_I4}};
static _ATL_FUNC_INFO OnError = {CC_STDCALL, VT_EMPTY, 2, {VT_I4, VT_BSTR}};
static _ATL_FUNC_INFO OnConnected = {CC_STDCALL, VT_EMPTY, 0};
static _ATL_FUNC_INFO OnAuthenticated = {CC_STDCALL, VT_EMPTY, 0};

class CMailEvents:public IDispEventSimpleImpl<IDC_SRCIMAIL, 
                                            CMailEvents, 
                                            &__uuidof(_IMailEvents)> 
{
public:
    CMailEvents(){};

BEGIN_SINK_MAP(CMailEvents)
    SINK_ENTRY_INFO(IDC_SRCIMAIL, __uuidof(_IMailEvents), 1, 
                    &CMailEvents::OnClosedHandler, &OnClosed)
    SINK_ENTRY_INFO(IDC_SRCIMAIL, __uuidof(_IMailEvents), 2, 
                    &CMailEvents::OnSendingHandler, &OnSending)
    SINK_ENTRY_INFO(IDC_SRCIMAIL, __uuidof(_IMailEvents), 3, 
                    &CMailEvents::OnErrorHandler, &OnError)
    SINK_ENTRY_INFO(IDC_SRCIMAIL, __uuidof(_IMailEvents), 4, 
                    &CMailEvents::OnConnectedHandler, &OnConnected)
    SINK_ENTRY_INFO(IDC_SRCIMAIL, __uuidof(_IMailEvents), 5, 
                    &CMailEvents::OnAuthenticatedHandler, &OnAuthenticated)
END_SINK_MAP()

public:
    BOOL	m_bError;
    BOOL	m_bFinished;
    _bstr_t m_lastError;

protected:
    HRESULT __stdcall OnClosedHandler()
    {
        m_bFinished = TRUE;
        return S_OK;
    }

    HRESULT __stdcall OnSendingHandler( long nSent, long nTotalSize )
    {
        _tprintf( _T("Sending %d/%d ...\r\n"), nSent, nTotalSize );
        return S_OK;
    }

    HRESULT __stdcall OnErrorHandler( long nErrorCode, BSTR ErrorMessage )
    {
        m_bFinished = TRUE;
        m_bError = TRUE;
        m_lastError = ErrorMessage;
        return S_OK;
    }

    HRESULT __stdcall OnConnectedHandler()
    {
        _tprintf(_T("Connected\r\n"));
        return S_OK;
    }

    HRESULT __stdcall OnAuthenticatedHandler()
    {
        _tprintf(_T("Authenticated\r\n"));
        return S_OK;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    ::CoInitialize( NULL );

    IMailPtr oSmtp = NULL;
    oSmtp.CreateInstance( "EASendMailObj.Mail");
    oSmtp->LicenseCode = _T("TryIt");
    
    //Set your sender email address
    oSmtp->FromAddr = _T("test@emailarchitect.net");
    //Add recipient email address
    oSmtp->AddRecipientEx( _T("support@emailarchitect.net"), 0 );
    //Set email subject
    oSmtp->Subject = _T("email from Visual C++ project in asynchronous mode ");
    //Set email body
    oSmtp->BodyText = _T("this is a test email sent from Visual C++ asynchronously");
    
    //Your smtp server address
    oSmtp->ServerAddr = _T("smtp.emailarchitect.net");
    //User and password for ESMTP authentication, if your server doesn't 
    //require User authentication, please remove the following codes.
    oSmtp->UserName = _T("test@emailarchitect.net");
    oSmtp->Password = _T("testpassword");

    //If your smtp server requires SSL connection, please add this line
    //oSmtp->SSL_init();

    _tprintf(_T("Start to send email ...\r\n" ));
  
    //Attach event connection pointer
    CMailEvents oEvents;
    oEvents.DispEventAdvise( oSmtp.GetInterfacePtr());
    oEvents.m_bFinished = FALSE;
    oEvents.m_bError = FALSE;

    //Set asynchronous mode
    oSmtp->Asynchronous = 1;
    oSmtp->SendMail();
    
    //waiting for email sending ...
    while( !oEvents.m_bFinished  )
    {
        MSG msg; 
        while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        { 
            if(msg.message == WM_QUIT) 
                return 0; 

            TranslateMessage(&msg); 
            DispatchMessage(&msg); 
        }  		
        //you can do other thing here
        ::Sleep(10);
    }

    //detach event connection pointer
    oEvents.DispEventUnadvise(oSmtp.GetInterfacePtr());
    if( !oEvents.m_bError )
    {
        _tprintf( _T("email was sent successfully!\r\n"));
    }
    else
    {
        _tprintf( _T("failed to send email with the following error: %s\r\n"),
            (const TCHAR*)oEvents.m_lastError);
    }

    if( oSmtp != NULL )
        oSmtp.Release();

    return 0;
}

Send email with Multiple Threads(Mass Mail)

FastSender object has an inner threading pool based on MaxThreads count. Firstly, Send method submits email to FastSender mail queue. Secondly threading pool retrieves email from mail queue and sends it out. Finally OnSent event informs that the email was sent successfully or unsuccessfully.

No. of worker threads in the threading pool of FastSender object is automatically adjusted based on the actual usage. The maximum no. of worker threads is up to the value of MaxThread property specified.

The following sample codes demonstrate how to send mass emails with FastSender object in Visual C++

/*[Visual C++ Example - Send Mass Emails with  Multiple Threads(Mass Mail)]*/
#include "stdafx.h"
#include <atlbase.h>
#include <atlcom.h>

#include "easendmailobj.tlh"
using namespace EASendMailObjLib;

#define IDC_SRCFASTSENDER 1

static _ATL_FUNC_INFO OnSent = {CC_STDCALL, VT_EMPTY, 6, 
    {VT_I4, VT_BSTR, VT_I4, VT_BSTR, VT_BSTR, VT_BSTR }};

class CFastSenderEvents:public IDispEventSimpleImpl<IDC_SRCFASTSENDER, 
                                            CFastSenderEvents, 
                                            &__uuidof(_IFastSenderEvents)> 
{
public:
    CFastSenderEvents(){};

BEGIN_SINK_MAP(CFastSenderEvents)
    SINK_ENTRY_INFO(IDC_SRCFASTSENDER, __uuidof(_IFastSenderEvents), 1, 
                &CFastSenderEvents::OnSentHandler, &OnSent)
END_SINK_MAP()

public:
    INT		m_nSent;
protected:
    HRESULT __stdcall OnSentHandler( long lRet, 
        BSTR ErrorDesc, 
        long nKey, 
        BSTR tParam, 
        BSTR Sender, 
        BSTR Recipients )
    {
        _bstr_t rcpt = Recipients;
        if( lRet == 0 )
        {
            _tprintf( _T("email was sent to %s successfully\r\n"), (const TCHAR*)rcpt );
        }
        else
        {
            _bstr_t error = ErrorDesc;
            _tprintf( _T("failed to sent email to %s with error %s \r\n"), 
                (const TCHAR*)rcpt, (const TCHAR*)error );
        
        }
        m_nSent++;
        return S_OK;
    }
};
int _tmain(int argc, _TCHAR* argv[])
{
    ::CoInitialize( NULL );
    const INT nRcpt = 3;
    const TCHAR* arRcpt[nRcpt] = {
        _T("test@adminsystem.com"), 
        _T("test1@adminsystem.com"),
        _T("test2@adminsystem.com")
    };

    IFastSenderPtr oFastSender = NULL;
    oFastSender.CreateInstance("EASendMailObj.FastSender");
    
    CFastSenderEvents oEvents;
    oEvents.DispEventAdvise( oFastSender.GetInterfacePtr());
    oEvents.m_nSent = 0;

    IMailPtr oSmtp = NULL;
    oSmtp.CreateInstance( "EASendMailObj.Mail");
    oSmtp->LicenseCode = _T("TryIt");

    //Set your sender email address
    oSmtp->FromAddr = _T("test@emailarchitect.net");

    //Your smtp server address
    oSmtp->ServerAddr = _T("smtp.emailarchitect.net");
    //User and password for ESMTP authentication, if your server doesn't
    //require User authentication, please remove the following codes.
    oSmtp->UserName = _T("test@emailarchitect.net");
    oSmtp->Password = _T("testpassword");

    //If your smtp server requires SSL connection, please add this line
    //oSmtp->SSL_init();
    
    for( int i = 0; i < nRcpt; i++ )
    {
        oSmtp->ClearRecipient();
        oSmtp->AddRecipientEx( arRcpt[i], 0 );
        oSmtp->Subject = _T("test mass email from visual c++");
        oSmtp->BodyText = _T("mass email test body sent from Visual C++");
        //submit email to inner thread pool
        oFastSender->Send( oSmtp, i, _T("anything"));
    }

    //waiting for all email finished.
    while( oEvents.m_nSent < nRcpt )
    {
        MSG msg; 
        while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        { 
            if(msg.message == WM_QUIT) 
                return 0; 

            TranslateMessage(&msg); 
            DispatchMessage(&msg); 
        }  		
        ::Sleep(10);		
    }

    oEvents.DispEventUnadvise(oFastSender.GetInterfacePtr());
    oSmtp.Release();
    oFastSender.Release();

    return 0;
}

Total Sample Projects

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

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

See Also

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

Free Email Support

Not enough? Please contact our technical support team.

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

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



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