Sending Email with PHP, Gmail or Google Apps, Mail, and PEAR on Ubuntu

First Install Pear, Mail, Mail Mime, Net SMTP. Restart Apache:

sudo apt-get install php-pear
sudo pear install mail
sudo pear install mail_mime
sudo pear install Net_SMTP
sudo /etc/init.d/apache2 restart

Here is the PHP code I used to send an email:

try {
	require_once "Mail.php";
 
	$from = "[email protected]";
	$to = "{$email}";
	$subject = "Hi!";
	$body = "Hi,\n\nHow are you?";
 
	$host = "ssl://smtp.gmail.com";
	$port = "465";
	$username = "[email protected]"; //This can also be a Google Apps account
	$password = "PASSWORD";
 
	$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("<p>" . $mail->getMessage() . "</p>");
	 } else {
	  echo("<p>Message successfully sent!</p>");
	 }
} catch (Exception $e) {
	echo 'Caught exception: ',  $e->getMessage(), "\n";
}
Facebooktwittergoogle_pluspinterest