Building a Secure OTP Email Sender with PHP and PHPMailer

Introduction

Hello friends, as we know paramount in today’s digital age. One of the most common methods to enhance security is the use of One-Time Passwords (OTPs). In this blog post, we’ll create a simple and  effective OTP email sender using PHP and PHPMailer. This project will allow you to send OTPs to users via email, ensuring an added layer of security for your applications.

Why Use OTPs?

OTPs are a secure way to authenticate users because they are:

  • Time-sensitive: They expire after a short period, reducing the risk of unauthorized access.
  • Unique: Each OTP is generated randomly, making it difficult for attackers to predict.
  • Convenient: Users can receive OTPs via email or SMS, making the authentication process easy and user-friendly.

Project Requirements

Before implementation, make sure you have the following:

  • PHP 7.x or higher
  • Composer
  • PHPMailer library

Getting Starated

Step 1: Clone the Repository

First, you’ll need to clone the repository to your local machine. Open your terminal and run the following command:

git clone https://github.com/quickalerts/otp-sender.git
cd otp-sender

Step 1: Install Dependencies

Navigate to the project directory and install the required dependencies using Composer:

composer install

Step 3: Project Structure

Your project directory should look like this:

otp-sender/
├── vendor/
├── index.php
├── composer.json
└── composer.lock

Composer.json

The composer.json file is very import file for any PHP project using Composer. It contains metadata about your project, including dependencies, scripts, and other configurations. Here’s an example of what composer.json might look like for this project:

{
    "name": "quickalerts/otp-sender",
    "description": "A simple OTP email sender using PHP and PHPMailer",
    "require": {
        "phpmailer/phpmailer": "^6.5"
    }
}

composer.lock

This file is automatically generated by Composer and it should not be edited manually. This file ensures that all developers working on the project use the same versions of dependencies. It records the exact versions of each package installed, along with other metadata.

When you run composer install, Composer reads the composer.lock file to install the specified versions of the dependencies.

Implementation

The heart of this project is in the index.php file, which handles the functionality of generation and sending of OTPs. Let’s create your own project:

  1. Generating OTPs: The generateOtp fuction creates a random 6 digit OPT.
  2. Form Submission: When the user submits their email address, the form data is processed.
  3. PHPMailer Configuration: PHP Mailer is configured to use Gmail’s SMTP server to send the email.
  4. Sending the OPT: The OPT is sent to the user’s email address.

Here is a snippet of the index.php code:

require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

function generateOtp() {
    return str_pad(rand(0, 999999), 6, '0', STR_PAD_LEFT);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $_POST['email'];
    $otp = generateOtp();
    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host       = 'smtp.gmail.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = '[email protected]';
        $mail->Password   = 'your-smtp-password';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;
        $mail->setFrom('[email protected]', 'Quick Alerts');
        $mail->addAddress($email);
        $mail->isHTML(true);
        $mail->Subject = 'Your OTP Code';
        $mail->Body    = "Your OTP code is: <b>$otp</b>";
        $mail->send();
        echo 'OTP has been sent to your email!';
    } catch (Exception $e) {
        echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }
}
?>

Step 4: Configuration

Before running the project, make sure to modify the following components of email configuration in index.php:

$mail->Host       = 'smtp.gmail.com';
$mail->Username   = '[email protected]';
$mail->Password   = 'your-smtp-password';

Usage

To use this project:

  1. Place the project directory in your web server root (e.g., htdocs for XAMPP or www for WAMP).
  2. Open your web browser and navigate to http://localhost/otp-sender
  3. Enter your email address and click “Send OTP” to receive an OTP in your email.

You can find the source code for this project on GitHub: https://github.com/quickalerts/otpsender.git

Updated: 05/01/2025 — 6:07 PM

Leave a Reply

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