Categories
PHP

PHP script for sending the email from localhost

This is very simple way to send the email from localhost.

<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Sohel Rana
 * Date: 4/17/13
 * Time: 1:44 AM
 */
define('GUSER', 'your-email@gmail.com'); // GMail  Username
define('GPWD', 'your-password'); // GMail Password
require_once('lib/class.phpmailer.php');
/**
 * @param $To             Where we need to send the Email
 * @param $Subject        Subject of the Email
 * @param $SenderEmail    Who send the Email
 * @param $Message        Body fo the Email
 * @return bool           Return true if sent the email otherwise false
 */
function SendEmail($To, $Subject, $SenderEmail, $Message)
{
    $mail = new PHPMailer(); // create a new object
    $mail->IsSMTP(); // enable SMTP
    $mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
    $mail->SMTPAuth = true; // authentication enabled
    $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 465;
    $mail->Username = GUSER;
    $mail->Password = GPWD;
    $mail->IsHTML(true); // send as HTML
    $mail->Subject = $Subject;
    $mail->AddReplyTo($SenderEmail);
    $mail->Body = $Message;
    $mail->AddAddress($To);
    if ($mail->Send()) {
        return true;
    }
    else {
        return false;
    }
}

if(SendEmail('to@gmail.com', 'Test Email', 'from@gmail.com', "Hello World")) {
    echo 'Email Sent';
}
else {
    echo 'Email Not Sent';
}
?>

NB: Download the php-mailer library from here

By Sohel Rana

PHP Programmer, Software Engineer & Technology lover

Leave a Reply

Your email address will not be published. Required fields are marked *