Blog maintained by TechnoGems

Tuesday, October 11, 2011

Using PHPMailer and Gmail to send email

If you are developing applications using PHP and you need to send email you can use the PHPMailer() class in PHP. Using a publicly available SMTP server to send the email is much easier than trying to setup your own email server. The following code snippet shows the various settings for the mailer.
The code assumes that you have PHP 5.x version and you have class.phpmailer.php file in the include directory.
Google uses ssl for the smtp connection. In order for this example to work with google smtp server, you need to enable ssl in your php.ini file by adding a line that says extension=php_openssl.dll

If you are not sure of the exact location of the php.ini file and you are using xampp, you can find the location of the php.ini file by navigating to http://localhost/xampp/phpinfo.php on your browser and look for the text "Loaded Configuration File". Once you find the file, edit it and look for the text "extension=php_openssl.dll". If the text is not found in your file, add a new line at the end of the file with the above text.
IsSMTP();
$mail->SMTPDebug = 1; // 1 tells it to display SMTP errors and messages, 0 turns off all errors and messages, 2 prints messages only.

$mail->Host = "ssl://smtp.gmail.com"; // specify main and backup server
$mail->Port = 465; // set the port to use
$mail->SMTPAuth = true; // turn on SMTP authentication

$mail->Username = 'user@gmail.com'; // replace this with your email acct
$mail->Password = 'userPassword'; // replace this with your password

$mail->From = 'jmeslie@gmail.com';
$mail->FromName = 'Jean Meslie';
$mail->AddAddress('receipient@yahoo.com', 'Receiver');
$mail->AddReplyTo('user@gmail.com'); // Adds a “Reply-to' address. Un-comment this to use it.
$mail->Subject = 'test message';
$mail->Body = 'message body goes here. This message was sent at '. time();

if ($mail->Send() == true) {
echo 'The message has been sent at '. time();
}
else {
echo 'The email message has NOT been sent for some reason. Please try again later.';
echo 'Mailer error: ' . $mail->ErrorInfo;
}
?>

No comments: