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

Learn how to send email securely from your website using TLS with ASP.NET, PHP, WordPress and Classic ASP!
Published on Wednesday, 15 May 2013

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 emailadress@example.com 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">
  <head>
    <meta charset="utf-8" />
    <title>Saotn.org HTML5 contact/feedback form</title>
    <link rel="stylesheet" href="formstyle.css" type="text/css">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
  </head>
  <body>
  <h1>Contactform</h1>
  <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 -->  
    <fieldset>
      <legend>Your information</legend>
      <ol>
        <li>
          <label for="name">Name</label>
          <input id="name" name="name" type="text" 
            placeholder="First and lastname" title="format: first name last name"
            required autofocus>
        </li>
        <li>
          <label for="email">Email</label>
          <input id="email" name="email" type="email"
            title="example@example.com" placeholder="example@example.com"
            required>
        </li>
      </ol>
    </fieldset>
 
    <fieldset>
      <legend>Your feedback</legend>
      <ol>
        <li>
          <label for="message">Message</label>
          <textarea id="message" name="message" rows="10"
            required placeholder="Your message ..."></textarea>
        </li>
      </ol>
    </fieldset>
 
    <fieldset>
      <legend>Anti-spam code:</legend>
      <ol>
        <li>
          <label for="anti_spam">1 + 3 = </label>
          <input id="anti_spam" name="anti_spam" type="number"
            placeholder="answer the sum" required>
        </li>
      </ol>
    </fieldset>
 
    <fieldset>
      <button name="submit" type="submit">Send!</button>
    </fieldset>
  </form>
</body>
</html>

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');

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:

<?php
// telling the class to use SMTP
// support and donate: https://www.paypal.me/jreilink

$mail->IsSMTP();

/*
 * 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       = "smtp.example.com";
// set the SMTP port for the SMTP server, 587 might be possible too
$mail->Port       = 25;
// email address username
$mail->Username   = "emailadress@example.com";
// email address password
$mail->Password   = "password";
?>

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

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:

<?php
include('Mail.php');
 
$recipients = 'recipient@example.com';
 
$headers['From']    = 'emailadress@example.com';
$headers['To']      = 'recipient@example.com';
$headers['Subject'] = 'Test message';
 
$body = 'Test message';
 
$params["host"] = "smtp.example.com";
$params['auth'] = TRUE;
// email address username
$params['username'] = 'emailadress@example.com';
// 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.

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 ITFAQ.nl 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:

<system.net>
  <mailSettings>
    <smtp from="emailaddress@example.com" deliveryMethod="Network">
      <network host="smtp.example.com" port="25" userName="emailaddress@example.com" password="password">
      </network>
    </smtp>
  </mailSettings>
</system.net>

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) {
      SendMail();
    }
 
    void SendMail() {
      MailMessage NetMail = new MailMessage();
      SmtpClient MailClient = new SmtpClient();
      string ThisHost = "smtp.example.com";
      int ThisPort = 25;
      string EmailSender = "Website <website@example.com>";
      string EmailRecipient = "Name <recipient@example.com>";
 
      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
      //# /posts/add-custom-headers-to-mailmessage-class/
      NetMail.Headers.Add("Message-Id", "<" + Guid.NewGuid().ToString() + "@example.com>");
      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;
      MailClient.Send(NetMail);
 
      NetMail.Dispose();
      NetMail = null;
      MailClient = null;
    }
</script>

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)
      SendMail()
    End Sub
 
    Sub SendMail()
      Dim NetMail As New MailMessage
      Dim MailClient As New SmtpClient
      Dim ThisHost As String = "smtp.example.com"
      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() + "@example.com>");
      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
      MailClient.Send(NetMail)
 
      NetMail.Dispose()
      NetMail = Nothing
      MailClient = Nothing
    End Sub
</script>

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:

' http://msdn.microsoft.com/en-us/library/ms526318(v=exchg.10).aspx
' 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        = "http://schemas.microsoft.com/cdo/configuration/sendusing"
Const cdoSendUsingPort          = 2
Const cdoSMTPServer             = "http://schemas.microsoft.com/cdo/configuration/smtpserver"
Const cdoSMTPServerPort         = "http://schemas.microsoft.com/cdo/configuration/smtpserverport"
Const cdoSMTPConnectionTimeout  = "http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout"
Const cdoSMTPAuthenticate       = "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"
Const cdoBasic                  = 1
Const cdoSendUserName           = "http://schemas.microsoft.com/cdo/configuration/sendusername"
Const cdoSendPassword           = "http://schemas.microsoft.com/cdo/configuration/sendpassword"

' Use SSL for the connection (False or True)
Const cdoSendTLS        = "http://schemas.microsoft.com/cdo/configuration/smtpusessl"

' 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)        = "smtp.example.com"
  .Item(cdoSMTPServerPort)    = 25 ' SMTP port, 587 is possible too
  .Item(cdoSMTPAuthenticate)  = cdoBasic ' send using SMTP authentication
  .Item(cdoSendUserName)      = "emailadress@example.com"  ' 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.

Conclusion sending secure authenticated 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!