Send authenticated SMTP (auth-SMTP) over a TLS encrypted connection. 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) that you can easily integrate in 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.

Protip: Learn how to verify SMTP Auth options and StartTLS. Does your host support StartTLS and/or SMTP authentication?

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)

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|.asp|.aspx" method="post">
      <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>

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
You may find this post interesting too:   How to: Test MySQL database connectivity in ASP.NET, PHP, ASP

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:


Then we can instantiate the class:

$mail = new PHPMailer();

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";

See the readme for more information, options and examples.

Now we can send our email in PHP:

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

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

Using PHP PEAR/Mail

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 webspace if necessary) including the PHP class in your script and setting 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);

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.

You may find this post interesting too:   How to make Twenty Seventeen theme full width in WordPress

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.

.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">

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;

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

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

What? Still using classic ASP?

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.

You may find this post interesting too:   Monit monitoring on Ubuntu 14.04 VM on Hyper-V

CDOSYS is a built-in component in ASP.

Tip: 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 With

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

Still using classic ASP?
Honestly, are you still using classic ASP? Get real and switch to a newer technology like ASP.NET, PHP or JavaScript/Node.js! Classic ASP is outdated!

SMTP Auth and TLS in Node.js/Ghost?
If you are running Ghost as a blogging platform, I can imagine you want to send secure email with Ghost (using SMTP authentication and TLS encryption) from your IIS hosted Ghost blog.

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 protection of your 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.

Want to thank me?

If I’ve helped you out and you want to thank me, why not buy me a coffee?

buy me a coffee
Thank you