Configure PHP to Send Mails using External SMTP Server

Sending e-mails from website is a very task and almost all proper web applications have a need to send e-mails. This feature is available in PHP but by default PHP is configured to use the local SMTP server. However, this is not the only option you have. PHP can be configured to use an external SMTP server like Gmail for this purpose.

For that these additional packages will be required:

sudo apt-get install php-pear php-mail php-net-socket php-net-smtp php-mail-mime

Once the required packages have been installed, you can start sending the mails. Here is a sample PHP script I have created for the demo purpose:

<?php
   include("Mail.php"); // Actual path /usr/share/php/Mail.php
   include("Mail/mime.php"); // Actual path /usr/share/Mail/mime.php

   /* mail setup recipients, subject etc */
   $recipients = "destination@gmail.com";
   $headers["From"] = "youremail@gmail.com";
   $headers["To"] = "destination@gmail.com";
   $headers["Subject"] = "Mail Test (PEAR) 3";
   // Use this for Unicode messages
   $headers["Content-type"] = 'text/html; charset="UTF-8"';
  
   $mailmsg = "<div style='color:blue;'>Sample New Message<br />احمد</div>";
      
   $mime= new Mail_mime("\n");
   $mime->setHTMLBody($mailmsg);
      
   $mailmsg = $mime->get();
      
   $headers = $mime->headers($headers);
     
   /* SMTP server name, port, user/passwd */
   $smtpinfo["host"] = "smtp.gmail.com";
   $smtpinfo["port"] = "25";
   $smtpinfo["auth"] = true;
   $smtpinfo["username"] = "youremail@gmail.com";
   $smtpinfo["password"] = "";
   
   /* Create the mail object using the Mail::factory method */
   $mail_object =& Mail::factory("smtp", $smtpinfo);
   /* Ok send mail */
   $mail_object->send($recipients, $headers, $mailmsg);
?>

Load the page in the browser and you will be happy to see that it works! 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s