How to send authenticated SMTP over a TLS encrypted connection, in PHP, ASP and ASP.NET?

If you want to send email securely from your website, this post is for you! In this post I’ll provide some script examples for ASP, PHP, and ASP.NET (C# / VB.Net – System.Net.Mail) that you can easily integrate and use to securely send email from your website.

Send secure SMTP email from your website with authentication, over a TLS encrypted connection:

Nowadays more and more web hosting providers require authenticated SMTP and TLS encrypted connections to send emails from websites. As often over an alternative SMTP port like 587. Encryption with TLS is important to secure the connection which prevents eavesdropping by others.

In most cases you have to make script adjustments to take advantage of this to send your email over a TLS secured connection. How do YOU send secure email? ASP, PHP, ASP.NET (C# and VB.NET) code examples and snippets for SMTP authentication and TLS encryption for you. All for a better security and protection of your privacy.

Sometimes you may need to verify the existence of TLS encryption and SMTP AUTH options first. Does your host support StartTLS and/or SMTP authentication?

SMTP Authentication, often abbreviated SMTP AUTH, is an extension of the Simple Mail Transfer Protocol whereby an SMTP client may log on, using an authentication mechanism chosen among those supported by the SMTP server. In most environments and email address and its password are used to log on.

Transport Layer Security (TLS) and its predecessor, Secure Sockets Layer (SSL), are cryptographic protocols that provide communication security over the Internet. They use asymmetric cryptography for authentication of key exchange, symmetric encryption for confidentiality and message authentication codes for message integrity. Several versions of the protocols are in widespread use in applications such as web browsing, electronic mail, Internet faxing, instant messaging and voice-over-IP (VoIP).

The TLS protocol allows client-server applications to communicate across a network in a way designed to prevent eavesdropping and tampering.

Both are necessary for secure transport of your email, e.g from the website to the SMTP server.

Throughout the example, I’ll use as the email address -username- to log on to the SMTP server, and simply password as its password. Replace with your email address and password.

HTML5 feedback form – or contact form – example

Imagine the following HTML5 contact form – or feedback form – we use on our website to receive feedback email from our visitors. You can style this form with CSS3 if you’d like for some neat user experience features.

<!DOCTYPE html>
<html dir="ltr" lang="nl-NL">
    <meta charset="utf-8" />
    <title> HTML5 contact/feedback form</title>
    <link rel="stylesheet" href="formstyle.css" type="text/css">
    <script src=""></script>
  <p>Please give us your feedback</p>
  <form id="form1" action="sendmail.php" method="post">
  <!-- the above can be sendmail.aspx or sendmail.asp as well -->  
      <legend>Your information</legend>
          <label for="name">Name</label>
          <input id="name" name="name" type="text" 
            placeholder="First and lastname" title="format: first name last name"
            required autofocus>
          <label for="email">Email</label>
          <input id="email" name="email" type="email"
            title="" placeholder=""
      <legend>Your feedback</legend>
          <label for="message">Message</label>
          <textarea id="message" name="message" rows="10"
            required placeholder="Your message ..."></textarea>
      <legend>Anti-spam code:</legend>
          <label for="anti_spam">1 + 3 = </label>
          <input id="anti_spam" name="anti_spam" type="number"
            placeholder="answer the sum" required>
      <button name="submit" type="submit">Send!</button>
</html>Code language: HTML, XML (xml)

Authenticated SMTP and TLS with PHP using PHPMailer

PHPMailer is a powerful class written in PHP to send email. Some of the PHPMailer class features include:

  • Integrated SMTP support – send without a local mail server
  • Send emails with multiple TOs, CCs, BCCs and REPLY-TOs
  • Multipart/alternative emails for mail clients that do not read HTML email
  • Support for 8bit, base64, binary, and quoted-printable encoding
  • SMTP authentication with LOGIN, PLAIN, NTLM and CRAM-MD5 mechanisms

First we need to download PHPMailer and upload it to our website. The next step is to include the class.phpmailer.php class in your PHP script:

require_once('class.phpmailer.php');Code language: PHP (php)

Then we can instantiate the class:

$mail = new PHPMailer();Code language: PHP (php)

We only have to define some variables to send our our email using authenticated SMTP over a TLS encrypted connection:

// telling the class to use SMTP
// support and donate:


 * enables SMTP debug information (for testing)
 * 1 = errors and messages
 * 2 = messages only
$mail->SMTPDebug  = 2;
// enable SMTP authentication
$mail->SMTPAuth   = true;
// sets the prefix to the server
$mail->SMTPSecure = "tls";
// set the SMTP server
$mail->Host       = "";
// set the SMTP port for the SMTP server, 587 might be possible too
$mail->Port       = 25;
// email address username
$mail->Username   = "";
// email address password
$mail->Password   = "password";
?>Code language: HTML, XML (xml)

See the readme for more information, options and examples.

Now you can send your email in PHP:

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
else {
  echo "Message sent!";
}Code language: PHP (php)

The code above may be a bit outdated since newer PHPMailer versions. Do read the docs first.

Using PHP PEAR/Mail

Anyone still using PHP PEAR?

As PHPMailer, Mail, or PEAR/Mail is a PHP class you can download and include in your scripts to send email. Or it’s already available if your webhosting provider added PEAR support: see if there is any mention of PEAR in the PHP include_path with phpinfo().

Sending email using authenticated SMTP and TLS with PEAR/Mail is, like PHPMailer, nothing more than (download PEAR/Mail and upload to your web space if necessary), include the PHP class in your script and set some variables:

$recipients = '';
$headers['From']    = '';
$headers['To']      = '';
$headers['Subject'] = 'Test message';
$body = 'Test message';
$params["host"] = "";
$params['auth'] = TRUE;
// email address username
$params['username'] = '';
// email address password
$params['password'] = 'password';
// Create the mail object using the Mail::factory method
$mail_object =& Mail::factory('smtp', $params);
$mail_object->send($recipients, $headers, $body);
?>Code language: HTML, XML (xml)

From the docs:

Fortunately, when we use authentication with Pear Mail, the connection is automatically TLS.

How to send mail in ASP.NET using System.Net.Mail

The following C# and VB.NET code shows you how to send email using SMTP authentication in ASP.NET and System.Net.Mail’s MailMessage class. All this over a TLS encrypted SMTP connection.

In the .NET Framework (or ASP.NET) you can use the System.Net.Mail Namespace (FAQ / link 2) for sending secure email with SMTP authentication over a TLS encrypted connection. System.Net.Mail is the namespace used to send email if you are using the .NET Framework 2.0 or higher.

One thing to remember is: for ease of use, you can add your SMTP credentials (username, password) to your web.config configuration in the mailSettings node.

Quick note that SmtpClient is now obsolete. Use MailKit instead to send mail. I have an article on addressing this: SMTP e-mail versturen met .NET Core 3.1 (in Dutch).

.NET SMTP web.config configuration

Configure your application with the following web.config information:

    <smtp from="" deliveryMethod="Network">
      <network host="" port="25" userName="" password="password">
</>Code language: HTML, XML (xml)

How to send mail in C#: email script

A code example to use SmtpClient to securely and authenticated send email from your website. With “securely” I mean, the connection is TLS encrypted and the SMTP session is authenticated with a username and password combination of the sender.

I love to have the IIS website identifier, or INSTANCE_ID, available in the headers in case of abuse – you may leave that out:

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Net.Mail" %>
<script runat="server">
    protected void Page_Load(object sender, EventArgs e) {
    void SendMail() {
      MailMessage NetMail = new MailMessage();
      SmtpClient MailClient = new SmtpClient();
      string ThisHost = "";
      int ThisPort = 25;
      string EmailSender = "Website <>";
      string EmailRecipient = "Name <>";
      NetMail.From = new MailAddress(EmailSender);
      NetMail.To.Add(new MailAddress(EmailRecipient));
      NetMail.IsBodyHtml = false;
      NameValueCollection NVCSrvElements = Request.ServerVariables;
      string[] InstanceID = NVCSrvElements.GetValues("INSTANCE_ID");
        //# Add Message-id and custom headers to MailMessage class
        NetMail.Headers.Add("Message-Id", "<" + Guid.NewGuid().ToString() + ">");
      NetMail.Headers.Add("X-Instance-ID", Convert.ToString(InstanceID[0]));
      NetMail.Subject = "Test Subject C#";
      NetMail.Body = "Test Body " + DateTime.Now.ToLongTimeString();
      MailClient.EnableSsl = true;
      MailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
      MailClient.Host = ThisHost;
      MailClient.Port = ThisPort;
      NetMail = null;
      MailClient = null;
</script>Code language: HTML, XML (xml)

How to send mail in VB.NET

The same code snippet for sending secure email over a TLS encrypted connection with SMTP authentication, now in VB.NET.

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Net.Mail" %>
<script runat="server">
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    End Sub
    Sub SendMail()
      Dim NetMail As New MailMessage
      Dim MailClient As New SmtpClient
      Dim ThisHost As String = ""
      Dim ThisPort As Integer = "25"
      Dim EmailSender As String = "Sender "
      Dim EmailRecipient As String = "Recipient "
      NetMail.From = New MailAddress(EmailSender)
      NetMail.To.Add(New MailAddress(EmailRecipient))
      NetMail.IsBodyHtml = False
        NetMail.Headers.Add("Message-Id", "<" + Guid.NewGuid().ToString() + ">");
      NetMail.Headers.Add("X-Instance-ID", Request.ServerVariables("INSTANCE_ID"))
      NetMail.Subject = "Test Subject VB"
      NetMail.Body = "Test Body " & DateTime.Now.ToLongTimeString()
      MailClient.EnableSsl = True
      MailClient.DeliveryMethod = SmtpDeliveryMethod.Network
      MailClient.Host = ThisHost
      MailClient.Port = ThisPort
      NetMail = Nothing
      MailClient = Nothing
    End Sub
</script>Code language: HTML, XML (xml)

Here I provided you two examples to send email secure, with SMTP authentication over a TLS encrypted connection, in ASP.NET (C# and VB.NET).

Send mail from ASP using CDOSYS

When using classic ASP and CDOSYS, CDOSYS needs to be configured properly to send SMTP authenticated email via TLS encrypted connections.

Collaboration Data Objects (CDO) is a Microsoft technology that is designed to simplify the creation of messaging applications. CDOSYS is a built-in component in ASP. CDOSYS needs to be configured properly to utilize SMTP authentication and a TLS encrypted connections. Doing so also solves that nasty The “SendUsing” configuration value is invalid error message (cdo.message.1 error 80040220).

Did you know that properly configuring SMTP-AUTH and TLS in ASP CDOSYS also resolves that nasty The “SendUsing” configuration value is invalid error message (cdo.message.1 error 80040220)?

You need to use the CDO.Configuration object to set a number of parameters:

' Its good practice to use the module constants defined in the
' type library for the names.  The full names are used here to
' indicate that this is what is going on

Const cdoSendUsingMethod        = ""
Const cdoSendUsingPort          = 2
Const cdoSMTPServer             = ""
Const cdoSMTPServerPort         = ""
Const cdoSMTPConnectionTimeout  = ""
Const cdoSMTPAuthenticate       = ""
Const cdoBasic                  = 1
Const cdoSendUserName           = ""
Const cdoSendPassword           = ""

' Use SSL for the connection (False or True)
Const cdoSendTLS        = ""

' create CDOSYS objects
Set myMail = CreateObject("CDO.Message")
Set myMail.Configuration = CreateObject("CDO.Configuration")
Set Fields = myMail.Configuration.Fields

' CDOSYS SMTP configuration
With Fields
	.Item(cdoSendUsingMethod)   = cdoSendUsingPort
	.Item(cdoSMTPServer)        = ""
	.Item(cdoSMTPServerPort)    = 25 ' SMTP port, 587 is possible too
	.Item(cdoSMTPAuthenticate)  = cdoBasic ' send using SMTP authentication
	.Item(cdoSendUserName)      = ""  ' email address username
	.Item(cdoSendPassword)      = "password"
	.Item(cdoSendTLS)           = true 'send using TLS
	.Update 'update the configuration
End WithCode language: PHP (php)

This is it for sending email securely with classic ASP, just call your myMail. properties like From, To, Subject, TextBody and Send.

Conclusion sending secure SMTP email from your website

Web hosting providers more and more require you to use authenticated SMTP and TLS encrypted connections to send email from your website. This is a good thing. Yes, it requires you to code a bit more, and most older code examples found on Google don’t work anymore. But it does provide you with better security and privacy.

Your SMTP transmission can’t be intercepted and read by others any more, and by requiring authenticated SMTP, only you can send email from your account through the SMTP server.

Fortunately, it’s pretty easy to adjust your classic ASP, ASP.NET and PHP scripts to send an email over a TLS secured connection from your website. Even from Node.js/Ghost or WordPress!

Jan Reilink

Hi, my name is Jan. I am not a hacker, coder, developer or guru. I am merely an application manager / systems administrator, doing my daily thing at Embrace - The Human Cloud. In the past I worked for clidn and Vevida. With over 20 years of experience, my specialties include Windows Server, IIS, Linux (CentOS, Debian), security, PHP, websites & optimization. I blog at

Oldest Most Voted
Inline Feedbacks
View all comments
17/04/2018 20:40

erreur 80040213 erreur serveur que dois je faire ca marchez moi mais pas au bureau

Bill Williams
06/11/2017 22:45

The code for Classic asp is off-the-page for the critical bits.

13/11/2015 17:52

Hi JanR:

I do understand, when selected the SSL cipher
the TLS cipher it works just?

Steven Kelly
Reply to  Jan Reilink
05/12/2019 16:15

You talk about TLS, but the “smtpusessl” setting actually chooses SSL. To use TLS, change the end of your declaration at the start to “sendtls”:
Const cdoSendTLS = “”

(SSL encryption of SMTP was never an official RFC standard, used to be on port 465 rather than 25 or 587, doesn’t use STARTTLS, and has since been deprecated.)

Reply to  Jan Reilink
29/04/2020 14:52


I think they mean this line:

Const cdoSendTLS = “”

Your asking for TLS, but your referencing the SSL schema. Is that intentional?

the TLS schema is :

CDO TLS is not fully implemented. I have not managed to get it to work at all.