Sending emails from a localhost environment using PHP can be challenging due to server configurations. However, using a powerful library like PHPMailer makes this task considerably easier.
In this step-by-step guide, we’ll explore how to send emails from localhost in PHP using PHPMailer.
1. Introduction
Sending emails from localhost can be challenging due to differences in server configurations between localhost and production servers.
PHPMailer is a widely used PHP library that simplifies the process of sending emails by providing a clean and efficient API.
2. Setting Up a Local Server Environment
Ensure you have a local server environment like XAMPP, WampServer, or MAMP installed on your machine. These tools provide a local server stack that includes PHP and MySQL.
3. Installing Composer
Composer is a dependency manager for PHP that simplifies the process of including external libraries in your project.
If you don’t have Composer installed, download and install it from getcomposer.org.
4. Creating a PHP Project
Create a new directory for your PHP project and navigate to it using the command line.
mkdir php-email-project
cd php-email-project
5. Installing PHPMailer
Initialize a new Composer project in your project directory and require PHPMailer:
composer init
composer require phpmailer/phpmailer
Follow the prompts during the composer init
process to create a composer.json
file.
6. Generate App Password
This example uses Gmail, if you’re using it too, you’ll need to generate an app password.
To Generate a google app password, open the following link (make sure you are logged in and two-step verification is enabled), and generate an app password.
https://myaccount.google.com/apppasswords
- Enter the App Name and Create:
- Copy the Generated App Password
My Generated App Password is – “
tnxeizcecpwljdnt
” Note: there is no space.
7. Creating the Email Script
Create a new PHP file (e.g., send_email.php
) in your project directory. This script will use PHPMailer to send an email. In the following code, change the details according to yours:
<?php
require __DIR__ . "/vendor/autoload.php";
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
// Change the following details according to yours
$gmail = "[email protected]";
$app_password = "app_password";
$sender_name = "Sender Name";
$receiver_email = "[email protected]";
$mail_subject = "email subject";
$mail_body = "email body";
try {
//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);
$mail->isSMTP(); //Send using SMTP
//Enable SMTP debugging
//SMTP::DEBUG_OFF = off (for production use)
//SMTP::DEBUG_CLIENT = client messages
//SMTP::DEBUG_SERVER = client and server messages
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->Host = 'smtp.gmail.com'; //Set the SMTP server to send through
//TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
$mail->Port = 587;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->SMTPAuth = true; //Whether to use SMTP authentication
$mail->Username = $gmail; //SMTP username
$mail->Password = $app_password; //SMTP password
/** Set who the message is to be sent from
* For gmail, this generally needs to be the same as the user you logged * in as. */
$mail->setFrom($gmail, $sender_name);
// who will receive the email
$mail->addAddress($receiver_email);
// if you want to send email to multiple users, then add the email addresses you which you want to send.
//$mail->addAddress('[email protected]');
//$mail->addAddress('[email protected]');
$mail->isHTML(true);
$mail->Subject = $mail_subject; // Subject of the Email
$mail->Body = $mail_body; // Mail Body
//For Attachments
//$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // You can specify the file name
$mail->send();
echo "Email has been sent successfully.";
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
8. Sending the Email
Run the PHP script using the following command:
php send_email.php
This should output either “Email has been sent successfully.” or an error message.
9. Handling Errors
If you encounter errors, review the SMTP settings and ensure they match your email provider’s requirements.
Check for typos, and make sure your email provider allows SMTP access from your localhost.
10. Conclusion
By following this guide, you have successfully set up a PHP project to send emails from localhost using PHPMailer.
This approach allows you to test and develop email functionality locally before deploying your application to a production environment.
Experiment with different features of PHPMailer to customize and enhance your email sending capabilities based on your application’s requirements.