Sending email Using Gmail From Localhost in PHP

Sending email Using Gmail From Localhost in PHP

Sending an email using Gmail's SMTP server from localhost in PHP requires you to have a Gmail account, enable "Less secure apps" and "Allow less secure apps" in your Google account settings (though this is not recommended for security reasons), and use the PHPMailer library for sending emails.

Sending email Using Gmail in php

Learn the step-by-step process of sending emails with attachments using PHPMailer, Gmail's SMTP server, and your localhost environment. Enhance your web development skills and ensure secure email communication effortlessly.

Here's a step-by-step guide with an example:

Step 1: Set up PHPMailer

In this step, we prepare our PHP environment to use the PHPMailer library, which simplifies the process of sending emails through SMTP servers. You can download PHPMailer directly from its GitHub repository or use Composer, a PHP package manager, to install it.

  • Download PHPMailer: You can download PHPMailer from its official GitHub repository and include it in your project manually.
  • Use Composer: If you choose to use Composer, you install PHPMailer and its dependencies with a single command. Composer will manage the library's installation and dependencies for you.
composer require phpmailer/phpmailer

Step 2: Create a PHP script to send emails

In this step, you create a PHP script that will send an email. The script uses the PHPMailer library to handle the email sending process.

  • Use PHPMailer: We import the necessary classes and functions from the PHPMailer library by including the autoload.php file. This file is generated when you use Composer to install PHPMailer.
  • Create a PHPMailer Instance: We create an instance of the PHPMailer class, which will be used to configure and send the email.
  • Server Settings: We specify the SMTP server settings for Gmail. This includes settings like the hostname, SMTP authentication, Gmail username (your email address), password, SMTP encryption method (TLS), and the port to connect to.
  • Recipients: We set the sender's and recipient's email addresses and names. You should replace '[email protected]' and '[email protected]' with actual email addresses.
  • Content: We specify the email's subject, message body, and set the email format to HTML.
  • Try-Catch Block: We wrap the email-sending code in a try-catch block to handle any potential errors gracefully. If the email sends successfully, it displays a success message. If there's an error, it prints an error message.

Create a PHP script, for example, send_email.php, with the following code:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php'; // Path to the PHPMailer autoload.php file

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

try {
    //Server settings
    $mail->isSMTP(); // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com'; // Specify Gmail's SMTP server
    $mail->SMTPAuth = true; // Enable SMTP authentication
    $mail->Username = '[email protected]'; // Your Gmail email address
    $mail->Password = 'your_password'; // Your Gmail password
    $mail->SMTPSecure = 'tls'; // Enable TLS encryption
    $mail->Port = 587; // TCP port to connect to

    //Recipients
    $mail->setFrom('[email protected]', 'Your Name'); // Sender's email and name
    $mail->addAddress('[email protected]', 'Recipient Name'); // Recipient's email and name

    // Content
    $mail->isHTML(true); // Set email format to HTML
    $mail->Subject = 'Subject of the email';
    $mail->Body = 'This is the HTML message body <b>in bold!</b>';

    // Send the email
    $mail->send();
    echo 'Email sent successfully';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
?>

Step 3: Configure Gmail

Before running the PHP script, you need to make some adjustments in your Gmail account settings to allow the script to send emails using your account:

  • Allow Less Secure Apps: You need to enable "Less secure app access" in your Google account settings. This setting allows less secure applications (like the script we're writing) to access your Gmail account. However, this is not recommended for security reasons, and using OAuth 2.0 is a more secure alternative.

Step 4: Run the PHP script

Once you've configured the script and allowed less secure app access in your Gmail settings, you can execute the PHP script on your localhost development environment.

Please note that while this example helps you understand the basic process of sending emails using PHP and Gmail. it's important to implement stronger security measures in a production environment, such as using OAuth 2.0 for authentication and securely managing credentials. Storing passwords directly in code is not secure.

Execute the PHP script in your localhost environment. Ensure that you have replaced '[email protected]' and 'your_password' with your Gmail email and password.

Important Security Note: Enabling "Less secure apps" and hardcoding your Gmail password in a script can pose security risks. It's strongly recommended to use OAuth 2.0 for authentication and a more secure method for storing credentials in a production environment. This example is primarily for learning purposes and should not be used in a production environment without security enhancements.

Example with Attachment

Certainly! Sending an email with an attachment using Gmail's SMTP server from localhost in PHP can be done with PHPMailer as well. Here's an example that demonstrates how to send an email with an attachment:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php'; // Path to the PHPMailer autoload.php file

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

try {
    //Server settings
    $mail->isSMTP(); // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com'; // Specify Gmail's SMTP server
    $mail->SMTPAuth = true; // Enable SMTP authentication
    $mail->Username = '[email protected]'; // Your Gmail email address
    $mail->Password = 'your_password'; // Your Gmail password
    $mail->SMTPSecure = 'tls'; // Enable TLS encryption
    $mail->Port = 587; // TCP port to connect to

    //Recipients
    $mail->setFrom('[email protected]', 'Your Name'); // Sender's email and name
    $mail->addAddress('[email protected]', 'Recipient Name'); // Recipient's email and name

    // Attachments
    $mail->addAttachment('path_to_attachment_file.pdf', 'Attachment Name.pdf'); // Replace with the actual path and name of your attachment file

    // Content
    $mail->isHTML(true); // Set email format to HTML
    $mail->Subject = 'Email with Attachment';
    $mail->Body = 'This email contains an attachment.';

    // Send the email
    $mail->send();
    echo 'Email sent successfully';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
?>

In this example, we've added the following changes:

  1. Attachments: We use the addAttachment method to specify the file path and name of the attachment you want to include in the email. Replace 'path_to_attachment_file.pdf' with the actual path to your attachment file and 'Attachment Name.pdf' with the desired name for the attachment.

The rest of the script remains the same as the previous example, including SMTP server settings, sender, recipient, email content, and error handling.

Make sure to update your Gmail email and password in the script, and also ensure that the attachment file exists at the specified path.

Related posts

Write a comment