How to Send Mail from Localhost in PHP Using PHPMailer? Step-by-Step Guide

This guide will show you how to send mail from localhost in PHP using PHPMailer, a popular library for handling email sending in PHP

How to send mail from localhost in PHP using PHPMailer? Email functionality is an essential part of many web applications, whether for user notifications, password recovery, or transactional messages. However, sending emails directly from a localhost development environment can be challenging without the right tools. This guide will show you how to send mail from localhost in PHP using PHPMailer, a popular library for handling email sending in PHP.

Why Use PHPMailer?

While PHP’s built-in mail() function allows you to send emails, it has limitations:

  • Lack of encryption support (e.g., TLS or SSL).
  • Inability to authenticate with SMTP servers securely.
  • Minimal error handling and debugging capabilities.

PHPMailer addresses these limitations by providing:

  • SMTP authentication support.
  • SSL/TLS encryption.
  • Rich debugging options.
  • Easy integration with third-party email services (e.g., Gmail, Outlook).

Prerequisites

Prior to we get started, ensure you have the following:

  • Localhost server: Set up a local web server using tools like XAMPP, WAMP, or MAMP.
  • Composer: PHPMailer is available as a Composer package. Download & install Composer if you haven’t already.
  • SMTP credentials: You’ll need credentials from an email provider (e.g., Gmail SMTP, SendGrid, or your web hosting provider).

How to Send Mail from Localhost in PHP Using PHPMailer? Step-by-Step Guide

Step 1: Install PHPMailer

To install PHPMailer via Composer, follow these steps:

  1. Open a terminal or command prompt.
  2. Navigate to your project’s root directory.
  3. Run the following command:
    composer require phpmailer/phpmailer
    This command installs PHPMailer and its dependencies in the vendor directo

Step 2: Configure Your SMTP Server

For this guide, we’ll use Gmail’s SMTP server as an example. Gmail’s SMTP details are:

  • SMTP server: smtp.gmail.com
  • Port: 587 (TLS) or 465 (SSL)
  • Encryption: TLS or SSL

Make sure to enable “Allow less secure apps” or create an App Password for Gmail accounts. This enhances security when connecting through external applications.

Step 3: Write PHP Code to Send Email

Below is an example of how to sending an email using PHPMailer:

<?php
// Load Composer’s autoloader
require ‘vendor/autoload.php’;

// Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Create a new PHPMailer instance
$mail = new PHPMailer(true);

try {
// Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output (0 for no output, 2 for detailed output)
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = ‘smtp.gmail.com’; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = ‘[email protected]’; // SMTP username
$mail->Password = ‘your_password’; // SMTP password (or App Password)
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption, ssl also accepted
$mail->Port = 587; // TCP port to connect to

// Recipients
$mail->setFrom(‘[email protected]’, ‘Your Name’);
$mail->addAddress(‘[email protected]’, ‘Recipient Name’); // Add a recipient

// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = ‘Here is the subject’;
$mail->Body = ‘This is the HTML message body in bold!‘;
$mail->AltBody = ‘This is the plain text message body’;

// Send email
$mail->send();
echo ‘Message has been sent’;

} catch (Exception $e) {
echo “Message could not be sent. Mailer Error: {$mail->ErrorInfo}”;
}

Step 4: Test the Email Sending Functionality

  1. Save the above PHP code to a file, e.g., send_email.php.
  2. Place the file in your web server’s root directory (for example htdocs for XAMPP).
  3. Start your local server.
  4. Open a browser and navigate to http://localhost/send_email.php.
  5. If configured correctly, you should see a success message, and the email will be sent to the recipient.

Debugging Common Issues

  1. SMTP Connection Errors:
    • Ensure your local server can connect to external SMTP servers. Some ISPs block SMTP ports.
    • Use tools like telnet to test SMTP connectivity.
  2. Authentication Errors:
    • Double-check your SMTP username and password.
    • For Gmail, enable “permit less secure apps” or use an App Password.
  3. Firewall/Antivirus Blocking:
    • Temporarily disable your firewall or antivirus software to see if they’re blocking outgoing SMTP connections.
  4. PHPMailer Error Logs:
    • Enable verbose debugging by setting $mail->SMTPDebug = 2;.

Step 5: Customize for Your Project

You can customize the script to:

  • Send emails to multiple recipients:
    $mail->addAddress(‘[email protected]’, ‘Another Recipient’);
  • Add attachments:
    $mail->addAttachment(‘/path/to/file.pdf’);
  • Use HTML templates for email content:
    $mail->Body = file_get_contents(’email_template.html’);

Alternatives to PHPMailer

If PHPMailer doesn’t meet your requirements, consider alternatives like:

  • SwiftMailer: Another popular PHP library for email sending.
  • Symfony Mailer: Part of the Symfony framework but can be used independently.

Conclusion

How to send mail from localhost in PHP using PHPMailer? Using PHPMailer simplifies the process of sending emails from localhost in PHP. With features like SMTP authentication, encryption, and error handling, it’s a reliable tool for integrating email functionality into your applications. Whether you’re working on a development project or preparing for production, PHPMailer ensures your emails are sent securely and efficiently.

Leave a Comment

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

Scroll to Top