Categories
PHP

How to send email from localhost in php

Sending email from localhost is the big challenge for the php developer. It’s really easy to send the email from localhost. I am gonna show you how to do it.

Step 1: Download the latest PHP mailer library. You can download from here .

Step 2: Just see the code below, I hope you can do this.

<?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';
}
?>

This is the really easy way to send the email from localhost

By Sohel Rana

PHP Programmer, Software Engineer & Technology lover

Leave a Reply

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