When you test Apache, PHP and MySQL in localhost, you may find mail function does not work in PHP. Below is my experience using smtp.gmail.com to send email in php in Windows 7.
1) We need Mail.php installed from PEAR.
cd C:\php\PEAR
php go-pear.phar
I downloaded Mail package from http://pear.php.net/package/Mail/download
put it under C:\php\PEAR\Mail-1.2.0
I download Net_SMTP-1.4.4 from http://pear.php.net/package/Net_SMTP/download/
rename it as Net and put it under: C:\php\PEAR\Mail-1.2.0\Mail\Net
I download Net_Socket from http://pear.php.net/package/Net_Socket/download/
copy Socket.php to C:\php\PEAR\Mail-1.2.0\Mail\Net
2.) In php.in, add following:
extension=php_openssl.dll
include_path = ".;c:\php\includes;c:\php\PEAR\pear;c:\php\PEAR\Mail-1.2.0\Mail"
3) mytest_mail.php (replace to your gmail account and password)
----------------------------------------------------------------
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
//require_once "Mail.php";
require_once "c:/php/pear/Mail-1.2.0/Mail.php";
$from = "Sender <mygmailaccount@gmail.com>";
$to = "Recipient <mygmailaccount@gmail.com>";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";
$host = "ssl://smtp.gmail.com";
$port = "465";
$username = "mygmailaccount@gmail.com";
$password = "mygmailpassword";
$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>");
}
?>
4) Done! You will receive an email in gmail account when you run mytest_mail.php in localhost.
--------------------------------------------------------------------------------------------------------------------------
Another method is to use PHPMailer. The code is as follows:
<?phprequire("class.phpmailer.php");
$mailer = new PHPMailer();$mailer->IsSMTP();
$mailer->Host = 'ssl://smtp.gmail.com:465';
$mailer->SMTPAuth = TRUE;
$mailer->Username = 'myname@gmail.com';
// Change this to your gmail adress
$mailer->Password = 'mypassword'; // Change this to your gmail password
$mailer->From = 'myname@gmail.com'; // This HAVE TO be your gmail adress
$mailer->FromName = 'MyName'; // This is the from name in the email, you can put anything you like here
$mailer->Body = 'This is the main body of the email';
$mailer->Subject = 'This is the subject of the email';
$mailer->AddAddress('myname@gmail.com');
// This is where you put the email adress of the person you want to mail
if(!$mailer->Send())
{
echo "Message was not sent<br/ >";
echo "Mailer Error: " . $mailer->ErrorInfo;
}
else
{
echo "Message has been sent";
}?>
No comments:
Post a Comment