Click here to Skip to main content
Click here to Skip to main content

SMTP Client with SSL/TLS

By , , 6 May 2013
 

Introduction

I needed to send emails in a product written in C++, so I searched the Internet and found a great article: SMTP Client written by Jakub Piwowarczyk. However, many of my clients use SMTP servers that require secure connection (TLS or SSL), and the SMTP Client does not support it. So I had to add SSL/TLS support to the CSmtp class from SMTP Client before I could use it in my product. As I was new to SSL/OpenSSL, it did take me quite some time to learn how to use it properly, and to make the code work with several popular SMTP servers. I have also seen people searching the internet looking for a C++ implementation of SMTP/SSL/TLS, but just could not find one. So I decided to share the one I wrote, in the hope that it will save people who are not familiar with SSL some time.

Note that this article does not cover the details of SMTP. Please go to the original article SMTP Client if you need to know more about SMTP.

Background

There are 2 kinds of secure connections for SMTP, one is SSL and the other is TLS. Some SMTP servers support only one kind and some support both. Generally speaking, the port for SSL is 465, and the port for TLS is 587, but this is not always the case. In addition to the ports being different, SMTP/SSL is different than SMTP/TLS in that, SMTP/SSL negotiates an encrypted connection directly after the underlying TCP connection has been established, while SMTP/TLS requires that the client send a STARTLS command to the server before they negotiate an encrypted connection.

The steps involved in SMTP/SSL are as follows:

  1. The client connects to the server using TCP.
  2. The client negotiates an encrypted connection with the server.
  3. The server sends a welcome message using the encrypted connection to the client.
  4. The client sends a EHLO command using the encrypted connection to the server.
  5. The server responds to the EHLO command using the encrypted connection.

The steps involved in SMTP/TLS are as follows:

  1. The client connects to the server using TCP.
  2. The server sends a welcome message using the un-encrypted connection to the client.
  3. The client sends a EHLO command using the un-encrypted connection to the server.
  4. The server responds to the EHLO command using the un-encrypted connection.
  5. The client sends a STARTTLS command using the un-encrypted connection to the server.
  6. The server responds to the STARTTLS command using the un-encrypted connection.
  7. The client negotiates an encrypted connection with the server.
  8. The client sends a EHLO command using the encrypted connection to the server.
  9. The server responds to the EHLO command using the encrypted connection.

Using the Code

I have used openssl (http://www.openssl.org) in the sample code. The directory "openssl-0.9.8l" in the sample code contains all the necessary header files and the two pre-built static openssl libraries. If you would also like to use this version of openssl in your code, be sure to copy the entire "openssl-0.9.8l" directory to the root directory of your project and add "openssl-0.9.8l\inc32" to "Additional Include Directories", and also add "openssl-0.9.8l\out32" to "Additional Library Directories".

If you would like to build your own openssl, please refer to http://www.openssl.org for detailed instructions.

#define test_gmail_tls
    CSmtp mail;
#if defined(test_gmail_tls)
    mail.SetSMTPServer("smtp.gmail.com",587);
    mail.SetSecurityType(USE_TLS);
#elif defined(test_gmail_ssl)
    mail.SetSMTPServer("smtp.gmail.com",465);
    mail.SetSecurityType(USE_SSL);
#elif defined(test_hotmail_TLS)
    mail.SetSMTPServer("smtp.live.com",25);
    mail.SetSecurityType(USE_TLS);
#elif defined(test_aol_tls)
    mail.SetSMTPServer("smtp.aol.com",587);
    mail.SetSecurityType(USE_TLS);
#elif defined(test_yahoo_ssl)
    mail.SetSMTPServer("plus.smtp.mail.yahoo.com",465);
    mail.SetSecurityType(USE_SSL);
#endif
    mail.SetLogin("***");
    mail.SetPassword("***");
    mail.SetSenderName("User");
    // ......
    mail.Send();

If you use a non-privileged user account to test Yahoo, the mail will fail to send. And the error message returned by the Yahoo SMTP server is "530 Access denied: Free users cannot access this server".

Notes

  • The code does not verify the server's identity, that is, it does not check the server's certificate. This is usually not a big problem if we make sure we feed the program with correct server addresses. However, it is still worth mentioning that there is the chance that we are talking to an impersonator if we don't check the certificate.
  • You are not allowed to use the code in this article for spamming.

References

History

  • Rev 2.2, 2013/05/06

Thanks to everyone for the effective crowdsourcing!  Please keep up the improvements to our library!

  • Added fix contributed GKarRacer for the improper checking of the MsgBody.size() before working with a line of the message body.
  • Moved memory allocation and checking if all attachments can be opened to before the MAIL command is issued so that if there is an issue with one of them, sending the email can be gracefully aborted without the email being sent without the attachments.
  • Changed all the sprintf commands to snprintf to add greater security.  #define'd snprintf to sprintf_s for MS Visual C.  Also changed most strcpy calls to snprintf since the MS Visual C version of that function strcpy_s has the arguments re-ordered so it wouldn't be possible to use it without affecting portability.
  • Added fix contributed by jcyangzh about a possible infinite loop in the SayQuit function.
  • Added fixes contributed by sbrytskyy required to make the AUTH PLAIN login work properly.
  • Rev 2.1, 2012/11/06
  • Rev 2.0, 2011/06/23
    • Added the m_bAuthenticate member variable to be able to disable authentication even though it may be supported by the server. It defaults to true so if it is not set, the library will act as it would have before the addition.
    • Added the ability to pass the security type, m_type, the new m_Authenticate flag, the login and password into the ConnectRemoteServer function. If these new arguments are not included in the call, the function will work as it did before.
    • Added the ability to pass the new m_Authenticate flag into the SetSMTPServer function. If not provided, the function will act as it would before the addition.
    • Added fixes contributed by Martin Kjallman
    • Added fixes contributed by Karpov Andrey
    • Added fixes contributed by Jakub Piwowarczyk
  • Rev 1.9, 2010/08/19
    • Added PLAIN, CRAM-MD5 and DIGESTMD5 authorization.
    • Added a DisconnectRemoteServer() function and reconfigured the Send() function such that if you have already called the ConnectRemoveServer() function, it will use the existing connection and leave the connection open. This allows you to call ConnectRemoteServer(), then send multiple messages on the same connection. If this approach is used, you have to call DisconnectRemoteServer() to close the connection. If you call Send() without calling ConnectRemoteServer(), it will close the connection after sending. This change should be fully backward compatible.
  • Rev 1.8, 2010/08/09
  • 2010/08/03
    • Modified Introduction
  • 2010/08/02
    • Added note
  • 2010/08/01
    • Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Authors

David Johns
Web Developer
United States United States
Member
No Biography provided

John_Tang
Software Developer
China China
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralRe: Fixed AUTH PLAINmemberludohavil14 Feb '13 - 5:27 
Bugexception in SayQuit could lead to infinite loop.memberjcyangzh13 Dec '12 - 17:05 
GeneralRe: exception in SayQuit could lead to infinite loop.memberDavid Johns16 Dec '12 - 10:24 
GeneralRe: exception in SayQuit could lead to infinite loop.memberjcyangzh16 Dec '12 - 16:22 
Questionhow to add a socket proxy class on it? so that I can set socket4/5 proxy when I send email?memberASERERTA@#@s25 Nov '12 - 2:53 
Questionlooks like a bug in plain auth [modified]membersbrytskyy21 Nov '12 - 0:55 
AnswerRe: looks like a bug in plain authmemberDavid Johns3 Dec '12 - 15:18 
GeneralI have some changes for OS X use.memberDavembg19 Nov '12 - 8:26 
GeneralRe: I have some changes for OS X use.memberDavid Johns3 Dec '12 - 0:56 
GeneralMy vote of 5memberMichael Haephrati מיכאל האפרתי6 Nov '12 - 7:21 
QuestionPerfect for my needs. One issuememberMember 95677173 Nov '12 - 7:11 
QuestionProgram crashes sometimesmemberMember 953694724 Oct '12 - 6:43 
AnswerRe: Program crashes sometimesmemberMember 953694724 Oct '12 - 7:21 
GeneralRe: Program crashes sometimesmemberDavid Johns26 Oct '12 - 1:09 
GeneralRe: Program crashes sometimesmemberMember 953694726 Oct '12 - 3:09 
GeneralRe: further infomemberMember 953694726 Oct '12 - 5:16 
GeneralRe: further infomemberDavid Johns3 Nov '12 - 9:30 
QuestionDoes not work when GMAIL is setup with 2 factor authenticationmemberRichmond Umagat20 Oct '12 - 17:28 
GeneralWorking well with Visual C++ 2010memberTiago Mielczarski Germano16 Oct '12 - 11:06 
QuestionAwesome codememberaldur_disciple25 Sep '12 - 21:51 
QuestionCompiling code in VC++ 6.0membersantu9 Sep '12 - 23:27 
AnswerRe: Compiling code in VC++ 6.0membervaibhavbvp10 Sep '12 - 22:40 
Questionwith qq or 163 to send mail failedmemberjeansea19 Jul '12 - 16:48 
GeneralMy vote of 5membergndnet12 Jul '12 - 4:56 
GeneralMy vote of 5membergndnet29 Jun '12 - 14:35 
Questionwell donememberEvren Daglioglu28 Jun '12 - 0:44 
QuestionHow to embed image file into message?memberHimanshu Manjarawala31 May '12 - 20:03 
AnswerRe: How to embed image file into message?memberAlan P Brown31 May '12 - 23:40 
QuestionWant Dynamic Link Library for this codememberHimanshu Manjarawala30 May '12 - 1:03 
QuestionIs it support Unicode? [modified]memberHimanshu Manjarawala25 May '12 - 0:37 
AnswerRe: Is it support Unicode?memberTai khoan dang ky bang meo12 Jul '12 - 4:06 
Questioncrasyed while using smtp.163.com with wrong passwordmemberoknight11 May '12 - 2:22 
AnswerRe: crasyed while using smtp.163.com with wrong passwordmemberjeansea19 Jul '12 - 16:47 
GeneralRe: crasyed while using smtp.163.com with wrong passwordmemberDavid Johns3 Nov '12 - 17:44 
Questionsend to multiple usermemberneo.one10 May '12 - 7:58 
QuestionOpenssl 64 Bitmembervikas.kr10 May '12 - 4:30 
AnswerRe: Openssl 64 BitmemberJake G25 Jan '13 - 20:03 
QuestionThe subject contains the Chinese letters could not be sentmemberLeonHuang07261 May '12 - 16:28 
AnswerRe: The subject contains the Chinese letters could not be sentmemberJohn TWC1 May '12 - 17:33 
GeneralRe: The subject contains the Chinese letters could not be sentmemberLeonHuang07261 May '12 - 17:39 
Questioncan work with CyaSSL?memberMember 85519108 Apr '12 - 3:18 
BugBug. Mail sent by mail@domain.com.memberagenua.grupoi6820 Mar '12 - 4:05 
QuestionCan support NTLM?memberMember 865422719 Feb '12 - 23:15 
QuestionCan't compile [modified]memberCool Smith7 Feb '12 - 5:53 
AnswerRe: Can't compilememberAlan P Brown8 Feb '12 - 6:33 
GeneralRe: Can't compilememberCool Smith8 Feb '12 - 7:33 
GeneralSorry, can't help with .dllsmemberAlan P Brown8 Feb '12 - 21:21 
GeneralRe: Can't compilememberDavid Johns26 Oct '12 - 1:25 
QuestionUSE_SSL no member of CSmtpmembermmaa201227 Jan '12 - 13:27 
AnswerRe: USE_SSL no member of CSmtpmemberAlan P Brown2 Feb '12 - 23:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130513.1 | Last Updated 6 May 2013
Article Copyright 2010 by David Johns, John_Tang
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid