Send PHP mail via SMTP

Overview

When you use the PHP mail function, you are sending email directly from your web server. This can cause issues if the FROM address isn’t set properly or if your email isn’t hosted with DreamHost. Sending mail via SMTP is recommended as email is sent from the mail server rather than the web server. View the PHP mail troubleshooting article for details.

There are a few options to send PHP mail via SMTP. For example:

This article explains how to use the PEAR option.

When should you use this option?

You should only use this option if you’re creating a custom built mail form. If you’re using software such as WordPress, you should use the built-in tools or plugins to send via SMTP instead.

Configuring PEAR to send mail

The following steps walk you through how to enable this:

  • Visit the PEAR article to install PEAR on your web server.
  • Install the necessary PEAR Mail packages. Visit PEAR Troubleshooting for instructions. For example, you’ll need the Mail and Net_SMTP packages. [server]$ pear install –alldeps Mail
  • Create a PHP file that uses PEAR to send mail via SMTP.

Configuring PHP to send SMTP mail

The following example can be used to send SMTP mail using the PEAR Mail package.

Finding your mail hostname

Make sure to use your mail server name for the mail hostname. This would either be imap.dreamhost.com or pop.dreamhost.com, depending on the connection type you prefer. The example below uses the hostname of ‘imap.dreamhost.com’.

<?php

error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED ^ E_STRICT);

set_include_path("." . PATH_SEPARATOR . ($UserDir = dirname($_SERVER['DOCUMENT_ROOT'])) . "/pear/php" . PATH_SEPARATOR . get_include_path());
require_once "Mail.php";

$host = "ssl://smtp.dreamhost.com";
$username = "youremail@example.com";
$password = "your email password";
$port = "465";
$to = "address_form_will_send_TO@example.com";
$email_from = "youremail@example.com";
$email_subject = "Subject Line Here: " ;
$email_body = "whatever you like" ;
$email_address = "reply-to@example.com";

$headers = array ('From' => $email_from, 'To' => $to, 'Subject' => $email_subject, 'Reply-To' => $email_address);
$smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));
$mail = $smtp->send($to, $headers, $email_body);


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

Source