How to Send an Email in PHP (OOP)

Katherine Petalio-Amar
5 min readApr 8, 2022
Photo by Markus Winkler on Unsplash

In this tutorial, you will learn how to send an email in PHP using Gmail SMTP Server.

Email is an important method in every business, especially in communication, marketing, and engagement with their users, clients, or customers. It is also the easiest way to transmit digital data.

What to expect?

  • Will be able to send emails in PHP using Gmail SMTP.
  • Learn how to enable email sending in Gmail.
  • Create OOP for email sending
  • Easy configure SMTP Server Credentials

Prerequisite

Before we begin make sure you already have the following :

  • Apache Web Server and PHP. If you are working on your local PC/Laptop you can install either XAMPP (for Windows and Mac OS) or WAMP (for Windows only) or MAMP (for Mac OS only).
  • Basic knowledge of using Command Prompt.
  • Basic knowledge in PHP Object-Oriented Program (OOP)
  • Gmail Account. Current Gmail sending is 500 emails or 500 recipients in a day, the threshold is reset after 24 hours. If you have already reached the limit you can no longer send emails. To know more you can visit here.
  • Composer for PHP dependency (You can download it here)

Enable Gmail Account to Send Email via SMTP

To be able to use Gmail as an SMTP server you need some adjustments to your account security settings.

  • Login to your Gmail account, and go to your My Account.
  • Under security make sure that Use your phone to sign in and 2-Step Verification is OFF
  • You can also turn ON the 2-Step Verification, but this will require you to create your app password for your application or device. Which is a bit more complicated.
  • Turn ON Less secure app access.

Note: Changing security settings may take a while to reflect, it may take 1 hour or more.

Download and Extract PHPMailer Library

  • Download the PHPMailer library from this GitHub link, or you can directly download the .zip file here.
  • Move or Copy the downloaded file to your project directory.
  • On your terminal / CMD go to your project folder.
$ cd ~/yourProjectPath
  • Once you are on your project path run the composer
$ composer require phpmailer/phpmailer

On your project folder you must be able to see the following files and folder:

  1. composer.json
  2. composer.lock
  3. vendor

If you are seeing those files and folders you can now proceed with creating PHP Scripts.

Create your PHP Scripts

Here you will be creating OOP PHP Scripts for sending emails so that you can easily send emails throughout your project.

Create your config.php file this will store the credentials of your SMTP Server.

You just need to create a constant variable for SMTP Credentials. Which consist of the following:

  • SMTP_HOST — this is usually the domain name of the server using the prefix smtp. Ex. smtp.gmail.com, smtp.example.com
  • SMTP_USER — this is usually the email account.
  • SMTP_PASS — this is usually the email account password
  • SMTP_SECURITY — this can be SSL or TLS both are security protocols that can be used by SMTP servers. SSL came after TLS.
  • SMTP_PORT — this depends on the SMTP Server you are using every server can use a different port. Commonly they used 587, 25.
<?phpdefine("SMTP_HOST", "smtp.gmail.com");
define("SMTP_USER", "<your gmail account>");
define("SMTP_PASS", "<your gmail account password>");
define("SMTP_SECURITY", "tls");
define("SMTP_PORT", "587");
?>

Create index.php, this will be your main file where you will send your email.

We need to include your config.php on the index.php so that, you could access the constant variable you created for SMTP Credentials.

include 'config.php';

After that, you need to include the packages of PHPMailer Library.

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
//Load Composer's autoloader
require 'vendor/autoload.php';

Then initialized the PHPMailer Object.

//Create an instance; passing `true` enables exceptions
$phpMailer = new PHPMailer(true);

Create your class file for Send Mail. Just name it sendMail.php.

<?php

class SendMail{

private $_mail;

function __construct($mail){

$this->_mail = $mail;
}

public function send($recipient, $fromEmail, $fromName, $message, $subject, $attachments = array()) {

$this->_mail->isSMTP(); # Set mailer to use SMTP
$this->_mail->Host = SMTP_HOST; # Specify main and backup SMTP servers
$this->_mail->SMTPDebug = 0;
$this->_mail->SMTPAuth = true; # Enable SMTP authentication
$this->_mail->Username = SMTP_USER; # SMTP username
$this->_mail->Password = SMTP_PASS; # SMTP password
$this->_mail->SMTPSecure = SMTP_SECURITY; # Enable TLS encryption
$this->_mail->Port = SMTP_PORT; # TCP port to connect to
$this->_mail->IsHTML(true);
$this->_mail->CharSet = 'UTF-8';
$this->_mail->From = $fromEmail;
$this->_mail->FromName = $fromName;
$this->_mail->Subject = $subject;
$this->_mail->Body = $message;

if(count($attachments) > 0){
foreach($attachments as $attachment) {
$this->_mail->AddAttachment($attachment['file'], $attachment['name']);
}
}

$this->_mail->addAddress($recipient);

try {
if(!empty($recipient)){
return $this->_mail->send();
}else{
return false;
}
} catch (Exception $e) {
echo $e;
return false;
}

}

}
?>

Once you have set up your SendMail class, go back to your index.php file.

Include and initialized your SendMail class, and pass the $phpMailer object to your SendMail class.

include 'sendMail.php';

$sendMail = new SendMail($phpMailer);

Sending Email

Using your index.php file, you can now try sending emails.

//initialize data
$recipient = 'myMail@gmail.com';
$fromEmail = 'noreply@example.com';
$fromName = 'Example Company';
$message = 'Hello, <br>
This is your email send thru PHP.';
$subject = 'Your PHP Mail';
$sendMail->send($recipient, $fromEmail, $fromName, $message, $subject);

Debugging

If you encounter an issue with sending an email, you can use debug option to get specific details of the issue.

$this->_mail->SMTPDebug = 0;   # Enable verbose debug output

Debug Levels

  • SMTPDebug = 0;
    Debug Off. Debug level for no output.
  • SMTPDebug = 1;
    Debug Client. Debug level to show client -> server messages.
  • SMTPDebug = 2;
    Debug Client and Server. Debug level to show client -> server and server -> client messages.
  • SMTPDebug = 3;
    Debug Client, Server, and Connection. Debug level to show connection status, client -> server, and server -> client messages.
  • SMTPDebug = 4;
    Debug Low Level. Debug level to show all messages.

You can download the complete file here:

https://github.com/khatzie/sendMail

References:

If you have any questions, feel free to use the comment section below. I will try my best to help and solve any further issues. 😉

--

--

Katherine Petalio-Amar

I'm a Software Developer with experience in Web Development and Mobile App Development and a bit knowledgeable in Server Management.