How to send authenticated smtp mail in php

By | July 13, 2017

How guys, In this article i am going to tell you about to send authenticated smtp mail in php. PHP provide a function mail() to send mails but this is not send valid authenticated smtp emails because of this it might be possible that your email will to go to the spam or junk folder of email. To get rid off this problem we generally use smtp authenticated mail instead of simple php mail() function.

For the authenticated mails first we need to install PEAR mail packages. You can download and install this package from the link given below –


Once this pear mail package is installed on your server you are able to use mail class available in this package to send mail.

You need to configure your smtp server’s host name, port, user name and password. Please follow the script given below –

 require_once "Mail.php";
 $mail_from = " Sender Name <sender email>";
 $mail_to = "Recipient Name <recipient email>";
 $subject = "Subject line of mail";
 $mail_body = "Mail body or content to be sent on email";
 $hostname = ""; // SMTP Host name
 $port = "465"; // Smtp port
 $user_name = "smtp_username"; // Email for authentication 
 $password = "smtp_password"; // Password of the above email
 $headers = array ('From' => $from,
   'To' => $mail_to,
   'Subject' => $subject);
 $smtp = Mail::factory('smtp',
   array ('host' => $hostname,
     'port' => $port,
     'auth' => true,
     'username' => $user_name,
     'password' => $password));
 $mail = $smtp->send($mail_to, $headers, $mail_body);
 if (PEAR::isError($mail)) {
   echo("<p>Error Occurred : " . $mail->getMessage() . "</p>");
  } else {
   echo("<p>Mail sent successfully!</p>");

In the above script we are including Mail.php file of pear mail package which is a mail class to send mail after that we configure headers and smtp authentication details and then using send method on ¬†smtp object. It will send mail. If there is any error occurred it will throw an error otherwise each a message “Mail sent successfully”.

Now you have learned to send authenticated mail from php script. Now all email sent from this script will go to the inbox instead of spam or junk folder of emails.