How to send email using PEAR Mail


PHP Pear Mail is one of the best way to sending Emails in PHP. Although mail()  function is working well in PHP, I would like to use PEAR::Mail because, it has more advanced features that can be used in PHP.  For Example, If you are using PHP mail() function you need to give header values as string but, in PEAR::Mail you are using headers in proper array using key value pair. Please follow below code snippet to send mail using PHP PEAR.

function sendEmail($subject,$recipient,$body){
 // Defines sender's email address
 define('SENDER', ';       
 //  Recipient email
 define('RECIPIENT', $recipient);  
// SMTP password
  define('HOST', '; // SMTP host name  
 define('PORT', '587');  // SMTP port no.   
 // Other message information                                              
 require_once 'Mail.php';
 $headers = array (
   'From' => SENDER,
   'To' => RECIPIENT,
   'Subject' => SUBJECT);
 $smtpParams = array (
   'host' => HOST,
   'port' => PORT,
   'auth' => true,
   'username' => USERNAME,
   'password' => PASSWORD
   // Create an SMTP client.
  $mail = Mail::factory('smtp', $smtpParams);
 // Send the email.
 $result = $mail->send(RECIPIENT, $headers, BODY);
 if (PEAR::isError($result)) {
   echo("Email not sent. " .$result->getMessage() ."\n");
 } else {
   echo("Email sent!"."\n");

In the above code snippet I have included Mail.php, If you run the above PHP code without installing the PEAR::Mail package, You will get a Fatal Error of not finding Mail.php file. Below is the list of required packages.

  • Net_Socket-1.0.14
  • Net_SMTP-1.7.2
  • Mail-1.3.0
  • Auth_SASL-1.0.6
  • Mail_Mime-1.10.0

Once these packages are installed, pear path needs to be included into php.ini file. Now, You can run above function to send the mail using PEAR package.

Please comment below if you find any issue or error. Cheers!