How to send authenticated SMTP + TLS in PHP, ASP and ASP.NET

Authenticated SMTP and TLS script examples for ASP, PHP, ASP.NET (C#/VB.Net): if you want to send secure email from your website, over an TLS-encrypted connection, this post is for you! In this post I’ll provide some code examples that you can use to send secure, and authenticated, SMTP email from your website.

Send secure SMTP email from your website with authentication and 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.

Pro Tip: 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 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|.asp|.aspx" method="post">
    <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
$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.

This may interest you:   Exploit PHP's mail() to get remote code execution

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:

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

.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
        # https://www.saotn.org/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).

This may interest you:   How to: Test MySQL database connectivity in ASP.NET, PHP, ASP

Send mail from ASP using CDOSYS #

What? Still using classic ASP?

When using classic ASP and CDOSYS, ASP/CDOSYS needs to be configured properly to send SMTP authenticated email via TLS encrypted connections. CDO (Collaboration Data Objects) is a Microsoft technology that is designed to simplify the creation of messaging applications.

CDOSYS is a built-in component in ASP.

Did you know that proper SMTP-AUTH and TLS configuration in ASP/CDOSYS so also resolves that nasty The “SendUsing” configuration value is invalid error message (cdo.message.1 error 80040220? Therefore, 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.

But honestly, 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 email #

Web hosting providers more and more require you to use authenticated SMTP and TLS encrypted SMTP 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.


Show your support


If you want to step in to help me cover the costs for running this website, that would be awesome. Just use this link to donate a cup of coffee ($5 USD for example). And please share the love and help others make use of this website. Thank you very much!


About the Author Jan Reilink

My name is Jan. I am not a hacker, coder, developer, programmer or guru. I am merely a system administrator, doing my daily thing at Vevida in the Netherlands. With over 15 years of experience, my specialties include Windows Server, IIS, Linux (CentOS, Debian), security, PHP, websites & optimization.

follow me on:

Leave a Reply

5 Comments on "How to send authenticated SMTP + TLS in PHP, ASP and ASP.NET"

avatar
  Subscribe  
newest oldest most voted
Notify of
Urbano Ballesteros
Guest

Hi JanR:

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

Bill Williams
Guest

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

vieilleribiere
Guest

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