How to Send a PHP Email via SMTP with the PEAR

While using the PHP mail function, the email is sent directly from the web server. However, that can cause some problems, if you haven’t set the FROM address properly or the email is not hosted by the DreamHost.

That’s why using SMTP for sending emails is more preferable than using the web server.

In this article, we will show you how to use the PEAR option to send emails via SMTP accurately.

Configure PEAR for Sending Emails

In this section, you will see the steps that will walk you through how to configure PEAR.

Install PEAR

The first step is installing PEAR. All you need to do is visiting the PEAR article and installing PEAR on your web server.

Installing PEAR Mail Packages

The second step is installing the necessary PEAR Mail packages..

Generally, you may need the packages of Net_SMTP and Mail.

Generate a PHP File

The final step includes generating a PHP file, which will use PEAR for sending messages with SMTP.

Configure PHP for Sending Emails with SMTP

In this section, we will provide the code that will help you to send emails via SMTP. You need to generate a mail.php file with the code below:

<?php

error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED ^ E_STRICT);

require_once "Mail.php";

$host = "ssl://smtp.dreamhost.com";
$username = "[email protected]";
$password = "your email password";
$port = "465";
$to = "[email protected]";
$email_from = "[email protected]";
$email_subject = "Subject Line Here:";
$email_body = "whatever you like";
$email_address = "[email protected]";

$headers = ['From' => $email_from, 'To' => $to, 'Subject' => $email_subject, 'Reply-To' => $email_address];
$smtp = Mail::factory('smtp', ['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>";
}

?>

All you need is updating the highlighted fields.

Activate Gmail

If you use Gmail for sending emails via SMTP, then you are required to allow the application to access the Gmail address. Otherwise, the email will not be sent.

When to Use PEAR?

This option is used only while generating a custom built mail form. In other cases, especially when you use Wordpress, you are required to use plugins or built-in tools for sending emails via SMTP.