Send email using Gmail SMTP server through PHP Mailer

Published on : June 3, 2014

Author:

Category: PHP


Download latest PHP mailer

Now, just do as below.


require("php_mailer/class.phpmailer.php");
define('GUSER', 'testprofile'); // GMail username
define('GPWD', 'xxxxxxxxx'); // GMail password
function smtpmailer($to, $from, $from_name, $subject, $message)
{
	global $err_msg;
	$mail = new PHPMailer();  // create a new object
	$mail->IsSMTP(); // enable SMTP
	$mail->SMTPDebug = 0;  // debugging: 1 = errors and messages, 2 = messages only
	$mail->SMTPAuth = true;  // authentication enabled
	$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
	$mail->Host = 'smtp.gmail.com';
	$mail->Port = 465;
	$mail->Username = GUSER;
	$mail->Password = GPWD;
	$mail->SetFrom($from, $from_name);
	$mail->Subject = $subject;
	$mail->Body = $body;
	$mail->AddAddress($to);
	if(!$mail->Send()) {
		$err_msg = 'Mail error: '.$mail->ErrorInfo;
		return false;
	} else {
		$err_msg= 'Message sent!';
		return true;
	}
}
$to_email = 'example_1@test_email.com';
$from_email = 'example_2@test_email.com';
$from_name = 'Test Email 2';
$subject = 'Gmail SMTP';
$message = 'Mail through Gmail SMTP';
$email_rec = smtpmailer($to_email, $from_email, $from_name, $subject, $message);
echo $email_rec;