Sending E-mails in PHP with PHPMailer
Tags: php, web, webdev, programming
Published: 2023-03-10 16:25:22


- [Introduction](#introduction)
- [Requirements](#requirements)
- [Setup](#setup)
- [Sending Emails with PHPMailer](#sending-emails-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](https://github.com/PHPMailer/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:
  - [PHP](https://www.php.net/downloads.php) (version 7.2 or higher)
  - [Composer](https://getcomposer.org/download/)
  - A text editor (e.g. [VS Code](https://code.visualstudio.com/download))
  - Git (optional)


## Setup
First, clone the [repository](https://github.com/peteradeojo/sending-mails-with-phpmailer.git) for this tutorial into an empty repository or [download](https://github.com/peteradeojo/sending-mails-with-phpmailer) the source code and unzip.

```bash
$ git clone https://github.com/peteradeojo/sending-mails-with-phpmailer.git
```

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

```bash
$ cd sending-mails-with-phpmailer
$ composer install
```

This installs a couple of dependencies for us.
1. [PHPMailer](https://github.com/PHPMailer/PHPMailer) - the library we will use to send emails.
2. [DotEnv](https://github.com/vlucas/phpdotenv) - 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
<?php

require_once 'vendor/autoload.php';
```
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.
<br><br>

>### 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.
> 
> ```php
> // ... (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.

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

```php
// Import PHPMailer classes and exceptions
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
```

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

```php
// ... (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}";
}
```

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!