DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Prosper Ugbovo
Prosper Ugbovo

Posted on

How To Send Email Using PHPMailer in PHP

Introduction

In order to add email services to your PHP application, the PHPMailer class is the ideal choice. PHP frameworks of all kinds are supported (Laravel or Symfony are based on the SwiftMailer library, though, but it is still possible to use PHPMailer as well.) An HTML email with attachments is created using this sophisticated tool, which can then be sent out through SMTP or web server on your local network to a large number of recipients in real time. At the end of this article You'll be able to send a mail using the php library.

Prerequisites

The following criteria must be met in order to follow along with this guide:

  • A PHP development environment that runs at least PHP 7.0.
  • (Optional) Composer.

Installation

You can send emails using mail(), Sendmail or Qmail, or you can send them directly through SMTP servers.
Additional advanced features include:

  • SSL/SMTP Authentication
  • Attachments in fs, string, and binary
  • A plain-text email can be sent to clients that do not support HTML email.
  • An active development community maintains it secure and current.

Installing PHPMailer

You must install PHPMailer through Composer, a dependency management for PHP, starting with version 6.0 released in August 2017. This method is suggested by PHPMailer's developers on Github.
In your terminal, type the following code to install the library:

composer require phpmailer/phpmailer
Enter fullscreen mode Exit fullscreen mode

PHPMailer can be added manually if you don't want to install Composer in a testing environment, for example. PHPMailer source code files may be downloaded here. Once downloaded, transfer the PHPMailer folder to one of the include path directories provided in your PHP setup, then manually load each class file:

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

require 'path_to_PHPMailer/src/Exception.php';
require 'path_to_PHPMailer/src/PHPMailer.php';
require 'path_to_PHPMailer/src/SMTP.php';
Enter fullscreen mode Exit fullscreen mode

See the PHPMailer documentation on Github for comprehensive information on how to install the package without composer.

Use PHPMailer to send emails from a local server

The most likely scenario is that you will utilize HTML to create your email messageΒ  As a result, you'll be using HTML techniques and attributes to deliver the messages to recipients.
Include the autoload.php file created by Composer if you have used Composer to install:

require 'path/to/composer/vendor/autoload.php';
Enter fullscreen mode Exit fullscreen mode

This is how to use PHPMailer if you have manually installed it:

require 'path_to_PHPMailer/src/PHPMailer.php';
require 'path_to_PHPMailer/src/SMTP.php';
require 'path_to_PHPMailer/src/Exception.php';
Enter fullscreen mode Exit fullscreen mode

Then include the PHPMailer class: