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:

   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 = "";
   $headers["From"] = "";
   $headers["To"] = "";
   $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");
   $mailmsg = $mime->get();
   $headers = $mime->headers($headers);
   /* SMTP server name, port, user/passwd */
   $smtpinfo["host"] = "";
   $smtpinfo["port"] = "25";
   $smtpinfo["auth"] = true;
   $smtpinfo["username"] = "";
   $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! 🙂


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s