How to Send Email from Localhost in PHP

Most of the web projects have the email sending functionality. Before uploading to the live server email functionality need to be checked on the local server. But PHP mail() function will not work at the localhost. In this article, we’ll show how you can send email from localhost in PHP. Using this simple PHP script you can send email from any localhost server, like XAMPP, WAMP, or any others.

We’ll use PHPMailer for helping to send email from localhost. Not only the text email, you can send HTML email from localhost in PHP using PHPMailer. Download the PHPMailer from GitHub, also you can get it from our downloadable package.

To using Gmail SMTP server, you should need to change account access for less secure apps. Don’t worry! Just follow the below steps.

That enough!

At first, include PHPMailerAutoload.php file in your script and create an instance of PHPMailer class.
Set your Google email address as SMTP username and password as SMTP password.
Insert the HTML email body content into the $bodyContent variable.

require 'PHPMailer/PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->isSMTP();                            // Set mailer to use SMTP
$mail->Host '';             // Specify main and backup SMTP servers
$mail->SMTPAuth true;                     // Enable SMTP authentication
$mail->Username 'Email Address' // SMTP username
$mail->Password 'Email Account Password'// SMTP password
$mail->SMTPSecure 'tls';                  // Enable TLS encryption, `ssl` also accepted
$mail->Port 587;                          // TCP port to connect to

$mail->addAddress('');   // Add a recipient

$mail->isHTML(true);  // Set email format to HTML

$bodyContent '<h1>How to Send Email using PHP in Localhost by CodexWorld</h1>';
$bodyContent .= '<p>This is the HTML email sent from localhost using PHP script by <b>CodexWorld</b></p>';

$mail->Subject 'Email from Localhost by CodexWorld';
$mail->Body    $bodyContent;

$mail->send()) {
'Message could not be sent.';
'Mailer Error: ' $mail->ErrorInfo;
} else {
'Message has been sent';

You can send multiple attachments with email by using the following code.

// Add attachments
$mail->addAttachment('/tmp/image.jpg''new.jpg'); // Optional name


  1. Neha Singh Said...
    • CodexWorld Said...
  2. Sudi Omary Said...
  3. Samuel Said...
  4. Hans Said...
  5. Sankhnad Mishra Said...
  6. Shivateja Said...
  7. Vipul Said...
    • CodexWorld Said...
  8. Amir Said...
  9. Fatima Said...
    • CodexWorld Said...

Leave a reply

CodexWorld Newsletter

Subscribe CodexWorld updates via email and get every new post delivered to your inbox.