Sending email through Gmail using PHP
Sending email is often a necessary feature in web applications. Here’s how you can send email from PHP by using SMTP through Gmail.
First, you’re going to need two PEAR packages: Mail and Net_SMTP. Make sure the directory where these files are found is listed in the include_path directive in your php.ini file.
This is based largely on a code snippet from email.about.com. Modify according to your needs. Entries in bold are ones you will definitely need to change.
<?php
require_once('Mail.php');
$from = '<strong>Sender <sender@gmail.com></strong>';
$to = '<strong>Receiver <receiver@something.com></strong>';
$subject = '<strong>Sent from PHP on my machine</strong>';
$body = '<strong>This is a message I sent from PHP using the '
. 'PEAR Mail package and SMTP through Gmail. Enjoy!</strong>';
$host = 'smtp.gmail.com';
$port = 587; // Must be 465 or 587
$username = '<strong>sender</strong>';
$password = '<strong>your_password</strong>';
$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, $body);
if (PEAR::isError($mail)) {
echo $mail->getMessage();
} else {
echo "Message sent successfully!";
}
echo "\n";
?>