22 September 2010

How to send emails from localhost using php

Today through this article, I will describe How to send email using PHP from localhost

Most common function that you might be aware of is mail(), but it doesn't work on localhost, but using PHPMAILER you can send email from localhost even provided you have xampp or any other server installed on your machine

First of all, we will create a very simple form that includes a simple email and message field, you can use following code

<form method="post" action="sendmail.php">
  Email: <input name="email" id="email" type="text" /><br />
  Message:<br />
  <textarea name="message" id="message" rows="15" cols="40"></textarea><br />
  <input type="submit" value="Submit" />

Now we will create a file named sendmail.php and the following code, here we will use phpmailer class, you can download it from here: PHPMAILER


// $email and $message are the data that is being
// posted to this page from our html contact form
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;


$mail = new PHPMailer();

// set mailer to use SMTP

// As this email.php script lives on the same server as our email server
// we are setting the HOST to localhost

$mail->Host = "localhost";  // specify main and backup server

$mail->SMTPAuth = true;     // turn on SMTP authentication

// When sending email using PHPMailer, you need to send from a valid email address
// In this case, we setup a test email account with the following credentials:
// email: send_from_PHPMailer@bradm.inmotiontesting.com
// pass: password

//Replace this with your actual SMTP credentials

$mail->Username = "";  // SMTP username
$mail->Password = ""; // SMTP password
$mail->Port = "465"; //If ssl else 26

// $email is the user's email address the specified
// on our contact us page. We set this variable at
// the top of this page with:
// $email = $_REQUEST['email'] ;

$mail->From = $email;

// below we want to set the email address we will be sending our email to.
$mail->AddAddress("goyalmanish47@gmail.com", "Manish Goyal");

// set word wrap to 50 characters
$mail->WordWrap = 50;
// set email format to HTML

$mail->Subject = "You have received feedback from your website!";

// $message is the user's message they typed in
// on our contact us page. We set this variable at
// the top of this page with:
// $message = $_REQUEST['message'] ;
$mail->Body    = $message;
$mail->AltBody = $message;

   echo "Message could not be sent. <p>";
   echo "Mailer Error: " . $mail->ErrorInfo;

echo "Message has been sent";

If you want to use gmail smtp then simply replace following

$mail->Host = "smtp.gmail.com";
$mail->Username = "your gmail username "; // SMTP username
$mail->Password = "your gmail password"; // SMTP password

If any doubts then feel free to reach me