Test PHP SMTP functionality

  • Last updated on: 2015-12-29
  • Authored by: Rackspace Support

You can test PHP SMTP functions with the following two examples. The first one is standard SMTP, and the second one is SMTP with SSL.

We recommend that you use an SMTP relay that requires authentication. Because of stringent anti-spam filters, sending mail through unauthenticated SMTP servers (including the localhost relay on Cloud Sites) can result in delays or undelivered email.

Sending mail with PHP SMTP

For the following variables, replace the example values with the appropriate values for your system:

  • $from
  • $to
  • $subject
  • $body
  • $host
  • $username
  • $password

The host, username, and password values depend on the provider that you’re using to send your email. If you have a legacy Cloud Sites email account or are using Rackspace Email, the host is mail.emailsrvr.com, and the username is your email address. If you’re using another service such as Mailgun or Gmail to send email, you must provide the SMTP server for that service. You can access Mailgun server information in the Mailgun control panel.

<?php
require_once "Mail.php";

$from = "Web Master <webmaster@example.com>";
$to = "Nobody <nobody@example.com>";
$subject = "Test email using PHP SMTP\r\n\r\n";
$body = "This is a test email message";

$host = "mail.emailsrvr.com";
$username = "webmaster@example.com";
$password = "yourPassword";

$headers = array ('From' => $from,
  'To' => $to,
  'Subject' => $subject);
$smtp = Mail::factory('smtp',
  array ('host' => $host,
    'auth' => true,
    '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>");
}
?>

Sending mail with PHP SMTP with SSL

For the following variables, replace the example values with the appropriate values for your system:

  • $from
  • $to
  • $subject
  • $body
  • $host
  • $username
  • $password

    "; $to = "Nobody "; $subject = "Test email using PHP SMTP with SSL\r\n\r\n"; $body = "This is a test email message"; $host = "ssl://secure.emailsrvr.com"; $port = "465"; $username = "webmaster@example.com"; $password = "yourPassword"; $headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject); $smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password)); $mail = $smtp->send($to, $headers, $body); if (PEAR::isError($mail)) { echo("

    " . $mail->getMessage() . "

    "); } else { echo("

    Message successfully sent!

    "); } ?>

Note: Mail.php is a PEAR module and is installed on the server. It is included in the default include_path for PHP, so requiring it here works by default.

Related article

Test CDOSYS SMTP functionality

Continue the conversation in the Rackspace Community.