Good content takes time and effort to come up with.

Please consider supporting us by just disabling your AD BLOCKER and reloading this page again.







Send Email In PHP With PHPMailer


18th May 2020 5 mins read
Share On     Share On WhatsApp     Share On LinkedIn


In frameworks like Larvel, Symfony, Codeigniter Mail functionality is built in with minor efforts you will start sending the mails. But when you don't use any frameworks it's bit tricky but very easy to achieve.


In this article you will learn how to


  1. Download PHPMailer Manually & Using Composer
  2. Include In Your Project
  3. Configure SMTP Mail Settings
  4. Simple Email Example
  5. Add CC, BCC, ReplyTo
  6. Add Attachments

1) Download PHP Mailer


Download Manually


First head to GitHub repository with this link PHPMailer. On right side click on Clone Or Download button & download as ZIP.


Once you download you need to include in your project folder.


NOTE: I have renamed it to mailer folder for accessibility which including in project.


PHP Mailer Renamed To mailer Folder

PHP Mailer Renamed To mailer Folder


Download Via Composer


If your using composer then first go to your working project and run the following command to download as composer package


composer require phpmailer/phpmailer


With above command it will get included in vendor folder.


2) Including In Your Project


Once you have download now its time to include in your project.


Manually Download Usage


If you have downloaded the PHPMailer manually then you have include in the file with require as follows:


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

require './mailer/src/Exception.php';
require './mailer/src/PHPMailer.php';
require './mailer/src/SMTP.php';

Composer Download Usage


Here you just need to include the vendor's autoload.php file which is responsible to autoload your dependency class of your class like the following


<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Load Composer's autoloader
require 'vendor/autoload.php';

3) Configuring SMTP Mail Settings


Now we have included in our file lets configure SMTP connection for sending emails.


For the sake of easy understanding I have included the comments in the following code


//Server settings
// $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP();                          // Send using SMTP
$mail->Host       = 'smtp.sendgrid.net';  // Set the SMTP server to send through
$mail->SMTPAuth   = true;                 // Enable SMTP authentication
$mail->Username   = 'username';           // SMTP username
$mail->Password   = 'password';           // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port       = 587;                  // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above


The above is the basic settings for the normal SMTP connections. Here I have used sendgrid as an example as I use it. You can even use GMAIL for free emails.


4) Simple Email Example


Lets put together the above code and built a simple code to send the email. Here I am sending HTML mail


I want to demonstrate the manual package downloaded because many of them find it difficult. If your using composer then not need to require any files everything will be handled by autoload.php just make sure to include is as show in step 2


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

require './mailer/src/Exception.php';
require './mailer/src/PHPMailer.php';
require './mailer/src/SMTP.php';

try {
    //Server settings
    //Server settings
    // $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
    $mail->isSMTP();                          // Send using SMTP
    $mail->Host       = 'smtp.sendgrid.net';  // Set the SMTP server to send through
    $mail->SMTPAuth   = true;                 // Enable SMTP authentication
    $mail->Username   = 'username';           // SMTP username
    $mail->Password   = 'password';           // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
    $mail->Port       = 587;                  // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above

    //Recipients
    /** This is basically you, your company */
    $mail->setFrom('sender_email@example.com', 'SenderName');
    /** Add recipients this is basically your customers or who you want to add */
    $mail->addAddress('customer1@gmail.com', 'Customer Name');
    $mail->addReplyTo('customer2@yahoo.com'); //Name is options
    //$mail->addCC('cc@example.com');

    // Content
    $mail->isHTML(true);  // Set email format to HTML
    $mail->Subject = 'Subject of your email';
    $mail->Body    = 'Hi,<br/>This is HTML email<br/>Thanks & Regards<br/>StackCoder';

    $mail->send();
    
    $data = array(
        'status' => 'Congratulation',
        'message' => 'Your message sent successfully.'
    );
    echo json_encode($data);
    exit;
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error";
    /** Uncomment the following during development for detailed error information */
    // echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

5) Add CC, BCC, ReplyTo


In the above example we have seen sender, reply to example lets see how we can add more options to it.


I have explained everything in the code so that it will be very easy for you to understand.


//Recipients
/** This is basically you, your company */
$mail->setFrom('sender_email@example.com', 'SenderName');

/** Add recipients this is basically your customers or who you want to add */
$mail->addAddress('customer1@gmail.com', 'Customer Name');
$mail->addAddress('customer1@gmail.com') //Name is optional;


/** Sender name and replying mails can be different as shown below
    If you dont want different then you have to add same as below


    $mail->addReplyTo('sender_email@example.com', 'SenderName');
 */

$mail->addReplyTo('customer2@yahoo.com', 'Sender Name');


/** Add carbon copy mails over here, you can add multiple. Name is optional */
$mail->addCC('cc@example.com', 'Some Name');
$mail->addCC('cc@example.com');


/** You can add blind carbon copy emails over here. Name is options */
$mail->addBCC('bcc@example.com');
$mail->addBCC('bcc@example.com');

6) Adding Attachments


While sending emails there might arise the requirement to add attachments, whether it might be images, files or compressed folders.


In PHPMailer you can easily achieve it by using the following


// Attachments
$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$mail->send();


You need to add before $mail->send();


Conclusion


Hope you learnt something new. If you liked it then please share with your friends.


WHATS NEXT?


You might be interest to learn more on composer please find my whole article on it


How To Upload Image In PHP?

How To Uploads Files In PHP?

How To Install Packages Parallel For Faster Development In Composer

What Is Composer? How Does It Work? Useful Composer Commands And Usage

composer.json v/s composer.lock

Composer Install v/s Composer Update

Route Model Binding In Laravel & Change Default Column id To Another Column

How To Run Raw Queries Securely In Laravel

Laravel 7.x Multiple Database Connections, Migrations, Relationships & Querying

How To Install Apache Web Server On Ubuntu 20.04 / Linux & Manage It

How To Create / Save / Download PDF From Blade Template In PHP Laravel

How To Add Free SSL Certificate In cPanel With ZeroSSL & Certbot

How To Securely SSH Your Server & Push Files With FileZilla

How To Push Files To CPanel / Remote Server using FTP Software FileZilla

How To Install Linux, Apache, MYSQL, PHP (LAMP Stack) on Ubuntu

How To Cache Static Files With NGINX Server

Redirect www to a non-www website or vice versa

How To Create Free SSL Certificate With Lets Encrypt/Certbot In Linux (Single / Multiple Domains)

How To Install Linux, NGINX, MYSQL, PHP (LEMP Stack) on Ubuntu

PHP Built-In Web Server & Testing Your Development Project In Mobile Without Any Software

How To Do Google reCAPTCHA Integration In PHP Laravel Forms


Happy Coding :)








Author Image
AUTHOR

Channaveer Hakari

I am a full-stack developer working at WifiDabba India Pvt Ltd. I started this blog so that I can share my knowledge and enhance my skills with constant learning.

Never stop learning. If you stop learning, you stop growing