Tuesday, August 16, 2011

PHP- send email using PHPMailer and gmail for PHP5



PHPMailer for PHP 5 can be downloaded from
http://sourceforge.net/projects/phpmailer/files/phpmailer%20for%20php5_6/PHPMailer%20v5.1/PHPMailer_v5.1.zip/download

In this example, I extract the PHPMailer to my directory PHPMailer_v5.1. To use gmail as smtp server in PHPMailer, you need to create a gmail account and replace my user name and password
to yours. The smtp host in gmail is smtp.gmail.com. The port is 465 and smtp secure is ssl.

My Code:

<?php
require("PHPMailer_v5.1/class.phpmailer.php");

$mail = new PHPMailer();

$mail->IsSMTP(); // set mailer to use SMTP
$mail->From = "myname@gmail.com";
$mail->FromName = "myname";
$mail->Host = "smtp.gmail.com"; // specif smtp server
$mail->SMTPSecure= "ssl"; // Used instead of TLS when only POP mail is selected
$mail->Port = 465; // Used instead of 587 when only POP mail is selected
$mail->SMTPAuth = true;
$mail->Username = "myname@gmail.com"; // SMTP username
$mail->Password = "mypassword"; // SMTP password
$mail->AddAddress("myname@gmail.com", "myname"); //replace myname and mypassword to yours
$mail->AddReplyTo("myname@gmail.com", "myname");
$mail->WordWrap = 50; // set word wrap
//$mail->AddAttachment("c:\\temp\\js-bak.sql"); // add attachments
//$mail->AddAttachment("c:/temp/11-10-00.zip");

$mail->IsHTML(true); // set email format to HTML
$mail->Subject = 'test';
$mail->Body = 'test';

if($mail->Send()) {echo "Send mail successfully";}
else {echo "Send mail fail";}

?>

1 comment:

  1. hi Jiansen lu,
    am getting this error while run above code

    SMTP Error: Could not connect to SMTP host. Send mail fail

    how to solve this error help me...

    ReplyDelete