How do I send PHP mail via SMTP?

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.

The easiest way to enable SMTP mail with PHP is to use the PEAR Mail package.

The following steps walk you through how to enable this:

  1. Visit the PEAR article to install PEAR on your web server.
  2. 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 Mail
    [server]$ pear install Net_SMTP
    
  3. Create a PHP file that uses PEAR to send mail via SMTP.

The following example can be used to send SMTP mail using the PEAR Mail package. You only need to update the fields which are in bold. Make sure to use your mail cluster name for the mail hostname. For example, sub4.mail.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://sub4.mail.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>"); } ?>

If you’re using Google to host your email, you must change the $host line to the following:

$host = "ssl://smtp.gmail.com";

See also

Did this article answer your questions?

Article last updated .