DEV Community

Cover image for Sending E-mails in PHP with PHPMailer
Peter Ade-Ojo
Peter Ade-Ojo

Posted on

Sending E-mails in PHP with PHPMailer

Introduction

Welcome to this tutorial on how to send emails using PHP! Communication is key, and emails are an essential part of keeping in touch with your users. In this article, we will walk through the process of sending emails using PHP and PHPMailer - a powerful library for sending emails in PHP. We'll also cover how to configure PHPMailer to use SMTP, which is the most common way of sending emails on the web.

We understand that setting up emails can be daunting, but don't worry! We'll guide you through each step in a friendly and professional manner, ensuring you have everything you need to get started. As an added bonus, we'll show you how to use environment variables in this project - a useful technique for securely storing sensitive information like passwords and API keys.

So whether you're a beginner or a seasoned developer, let's dive in and learn how to send emails with PHP!

Requirements

To follow this tutorial, you will need the following installed on your computer:

Setup

First, clone the repository for this tutorial into an empty repository or download the source code and unzip.

$ git clone https://github.com/peteradeojo/sending-mails-with-phpmailer.git
Enter fullscreen mode Exit fullscreen mode

Next, navigate into the project directory and install the dependencies using Composer.

$ cd sending-mails-with-phpmailer
$ composer install
Enter fullscreen mode Exit fullscreen mode

This installs a couple of dependencies for us.

  1. PHPMailer - the library we will use to send emails.
  2. DotEnv - a popular library that allows us to use environment variables in our project.

Great point! Before we proceed with the email sending process, we need to create a .env file in the root directory of our project. This file will contain the environment variables that we'll use throughout our project, such as our SMTP credentials and email recipient addresses.

To load the .env file, we'll use the Dotenv\Dotenv class. We'll call the load() method to load the contents of the .env file into our project. To make things even simpler, we recommend copying the contents of the .env.example file into the .env file.

This way, you'll have a template for the environment variables you'll need, and you can fill in the appropriate values for your project. With that done, we'll be ready to move on to the next step and start sending emails with PHPMailer.

Sending Emails with PHPMailer

Firstly, navigate to the root directory of our project in your text editor and create a new file called index.php.

Next, we'll need to require the vendor/autoload.php file that was automatically generated by Composer when we installed our dependencies. This file contains all the dependencies that we installed and allows us to use them in our project.

To do this, we'll add the following line of code at the top of our index.php file:

<?php

require_once 'vendor/autoload.php';
Enter fullscreen mode Exit fullscreen mode

This code will include the autoload.php file located in the vendor directory of our project. With this done, we'll be able to use PHPMailer and any other dependencies that we've installed using Composer.


Using Environment Variables - You can Skip this part

Using environment variables is a best practice for protecting sensitive information such as credentials from being exposed in source control. To use environment variables in our project, we first need to load the .env file.

To do this, we can use the Dotenv\Dotenv class and call the createImmutable() method to create a new instance of the class. We'll pass in the __DIR__ constant as an argument to specify the current directory as the base directory for our project.

// ... (require autoload.php omitted for brevity)

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

$username = $_ENV['USERNAME'];

By using environment variables, we can keep sensitive information secure and prevent it from being exposed in our source code.



Import the necessary classes for PHPMailer by adding the following lines to the top of your index.php file:

// Import PHPMailer classes and exceptions
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
Enter fullscreen mode Exit fullscreen mode

Then, we can proceed with the rest of the code in our index.php file:

// ... (require autoload.php omitted for brevity)


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

try {
    //Server settings
    $mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output
    $mail->isSMTP(); //Send using SMTP
    $mail->Host = $_ENV['SMTP_HOST']; //Set the SMTP server to send through
    $mail->SMTPAuth = true; //Enable SMTP authentication
    $mail->Username = $_ENV['SMTP_USERNAME']; //SMTP username
    $mail->Password = $_ENV['SMTP_PASSWORD']; //SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable SSL encryption
    $mail->Port = $_ENV['SMTP_PORT']; //TCP port to connect to, use 587 for `PHPMailer::ENCRYPTION_STARTTLS` above

    //Recipients
    $mail->setFrom('from@example.com', 'Mailer');
    $mail->addAddress('johndoe@example.com', 'John Doe'); //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 <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
Enter fullscreen mode Exit fullscreen mode

In this code, we create a new instance of PHPMailer and configure its settings to send an email.

We set the SMTPDebug property to SMTP::DEBUG_SERVER to enable verbose debug output, which is useful for testing and troubleshooting.

We set the isSMTP property to true to indicate that we will send the email using SMTP.

We then set the SMTP server to send through, the SMTP authentication credentials, and the encryption settings. These values are loaded from the .env file using the $_ENV superglobal array.

Next, we set the recipients of the email using the setFrom and addAddress methods.

We set the email format to HTML using the isHTML method and then set the subject and body of the email using the Subject, Body, and AltBody properties.

Finally, we call the send method to send the email. If the email is sent successfully, we output a message to the user. If there is an error, we output a message with the error information.

I hope this helps you send emails in PHP using PHPMailer!

Latest comments (2)

Collapse
 
mangojai profile image
mangojai

Thanks for your tutorial. The git address is not working at the mo?

Collapse
 
peteradeojo profile image
Peter Ade-Ojo

Thanks for your comment. The git repo is still up but if you still have issues with it here's the link: github.com/peteradeojo/sending-mai...