Skip to content

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 on the same server.

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 Mail library to send emails via SMTP.

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 visit the official PEAR documentation and install PEAR on your web server.

Installing PEAR Mail Packages

The second step is installing the necessary PEAR Mail packages.

Generally, you may need the Net_SMTP and Mail packages. You can install them via the command line:

bash
pear install Mail Net_SMTP

Generate a PHP File

The final step includes generating a PHP file, which will use PEAR for sending messages with SMTP. Create a new file named mail.php in your project directory.

Configure PHP for Sending Emails with SMTP

In this section, we will provide the code that will help you to send emails via SMTP. Open the mail.php file and add the following code:

create mail.php file

php
<?php

error_reporting(E_ALL);

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 placeholder fields with your actual credentials.

Activate Gmail

If you use Gmail for sending emails via SMTP, you must use an App Password if you have 2-Step Verification enabled, as Google disabled "Less secure apps" access in May 2022. 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.

Note: PEAR Mail is deprecated and unmaintained. For modern PHP projects, consider using PHPMailer or Symfony Mailer instead.

Dual-run preview — compare with live Symfony routes.