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.
$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;


hektorhamelton said...

Thanks to the author for writing the post, it was quite necessary for me and liked it. I wrote a note on the ukwritings.com review about this. I will be happy if you read it and accept it. Thank you for your concern.

Tom said...

That is very cool, idea! I love it! For me It's kind of hardunderstandig stuff but, you are doing well! If you need some help in future for the essay or homework, you can ask for help this guys! They really know how to do it! Just text to them paper writing services and everything gonna be cool! Enjoy!