Testing SMTP with PHP

A simple recipe to test SMTP mailing using php.

There a a number of mail-related modules available for php. Some are more full-featured than others. The language by default lets you send messages through a host’s local MTA like sendmail or postfix running on the host, but doing so is not a best practice and not available in most environments because of that.

Sending mail through a remote relay usually requires the installation of additional modules, like PHP:Mail:Net::SMTP.

On Red Hat derived systems the packages needed to support this are:

php-pear-Mail
php-pear-Mail-Net-SMTP

If not already installed these will also load some other packages as dependencies, such as php-pear-Net-Socket, php-pear-Auth-SASL to support SSL/TLS encrypted connections and authentication.

Here’s a sample script adapted from one provided by Rackspace to test this functionality:

<?php
require_once "Mail.php";

$from = "Phil Lembo <phil@example.com>";
$to = "Inside Devs <insidedevs@example.com>";
$subject = "Test email using SMTP\r\n\r\n";
$body = "This is a test email using PHP Pear's Mail:Net:SMTP.";

$host = "smtp.example.com";
// $username = "webmaster@example.com";
// $password = "yourPassword";

$headers = array (
  'From' => $from,
  'To' => $to,
  'Subject' => $subject);
$smtp = Mail::factory('smtp',
  array (
    'host' => $host,
    'port' => 25,
    'auth' => false,
    // 'username' => $username,
    // 'password' => $password));
    ));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
  echo("<p>" . $mail->getMessage() . "</p>");
} else {
  echo("<p>Message successfully sent!</p>");
}
?>

In the above authentication is not being used, and the well-known port for SMTP messaging is being addressed (TLS encrypted SMTP usually uses port 587, although some systems use port 465 for compatibility with legacy SMTPS servers).

NOTE:

The following code can be used to test the basic mail via local MTA functionality that php comes with out of the box:

<?php
$to = "insidedevs@example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "phil@example.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>

This basically corresponds to the tried-and-true command line test of your local MTA:

echo "This is a test." | mail -s "Testing local mail" phil@example.com
This entry was posted in Development, System Administration, Web on by .

About phil

My name is Phil Lembo. In my day job I’m an enterprise IT architect for a leading distribution and services company. The rest of my time I try to maintain a semi-normal family life in the suburbs of Raleigh, NC. E-mail me at philipATlembobrothersDOTcom. The opinions expressed here are entirely my own and not those of my employers, past, present or future (except where I quote others, who will need to accept responsibility for their own rants).