PHP Mail() sending through SSL encrypted Gmail using PEAR


For the past couple years, Google has had a far superior email solution than anyone else, with the exception of Outlook, but that really serves a different purpose.  Google Sync offers instant synchronization of your Calendar, Email and Contacts between your computer, your phone, and the web based Gmail client that everyone knows and loves.  Now with Google Apps you can let Google host all the email accounts up in the Google Cloud, FOR FREE.


I was having some difficulty sending mail from a form using the PHP Mail().  The solution I chose was to use Mail::factory() provided by Mail.php from PEAR – PHP Extension along with SSL encrypted Gmail to send the emails.  PEAR was already installed on my server, but if its not on yours, the install docs can be found here.

[root@c2g]# pear install Mail
pear/Mail requires PEAR Installer (version >= 1.5.6), installed version is 1.4.9
No valid packages found
install failed

No luck, need to upgrade PEAR using –force as suggested by ‘pear upgrade pear’

[root@c2g]# pear upgrade --force pear

Now install the Mail extension

[root@c2g]# pear install Mail

At this point, require_once “Mail.php”; will allow you access to Mail::factory.  Here is the code to authenticate to Gmail, prepare and send the email.

<?php $error = array(); $values = array(); $success = false; if ($_POST['submit']) {         if(empty($_POST['value'])) $error['value'] = true;         $values = $_POST;         require_once "Mail.php";         if (empty($error)) {                 $subject = "The Email Subject";                 $from = "";                 $to = "";                 $message = $_POST['value'];                 $host = "ssl://";                 $port = "465";                 $username = "";                 $password = "$uper$ecr3tPassw0rd";                 $headers = array ('From' => $from,                         'To' => $to,                         'Subject' => $subject);                 $smtp = Mail::factory('smtp',                         array ('host' => $host,                                 'port' => $port,                                 'auth' => true,                                 'username' => $username,                                 'password' => $password));                 $mail = $smtp->send($to, $headers, $message);                 $values = array();                 $success = true;         } } ?>
This entry was posted in PHP, Wordpress and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *