PHP Sending Emails



In this code snippet, we’ll learn how to send emails with PHPMailer in PHP.

First, we’ll need to install the PHPMailer package. We’ll do that using a dependency manager for PHP called Composer. (See this tutorial if you want to know how to install Composer in the first place.)

Simply open up cmd, navigate to your project directory and run this command: composer require phpmailer/phpmailer to add the dependency. Then we’ll include it at the top of the file.

Next, I’ll make two associative arrays. One will hold the data required to compose a new email(content, recipient, seder, …) while the other will contain the client data to send the email(SMTP server, username and password of the sender,  …). Then I’ll pass these two arrays to a function called setupMailer() which will make a PHPMailer email object and return it.

Finally, the send() function of the previously mentioned email object is called to send the actual email.

Let’s see the example code below.


//Include dependencies///////////////////////////////////////////////////////////////////////////
//Get path to current file, go one level up and then go down to "\vendor\autoload.php"
$pathToComposerLoadFile = dirname(__FILE__) . "\\vendor\autoload.php";
//Include and run composer autoloader for our dependencies.
require_once $pathToComposerLoadFile;
//Specify what dependencies we'll be using.
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//Entry point////////////////////////////////////////////////////////////////////////////////////
//Compose new email.
$newEmail = [
    "recipientFirstName" => "recipients first name",
    "recipientLastName" => "recipients last name",
    "recipientEmail" => "recipients email address",
    "firstName" => "senders first name",
    "lastName" => "senders last name",
    "email" => "senders email",
    "CCEmailAddresses" => [
        "cc email", //If none leave empty.
    "BCCEmailAddresses" => [
        "bcc email", //If none leave empty.
    "subject" => "Hello",
    "body" => "<h1>Hello Bob!</h1>",
    "altBody" => "Hello Bob!",
    "attachements" => [
        //Multiple attachement can be added here.
            "attachementPath" => "C:\\xampp\htdocs\Code Examples\php\Zipping Files",
            "attachementName" => "hello.text",
//Set emailer settings.
$emailSettings = [
    "host" => "", //Depends on your email provider. For example, outlook: "", gmail: "", ...;
    "port" => 587,
    "userName" => "YourEmailAddress",
    "password" => "YourEmailAddressPassword",
//Setup mailer.
$mail = setUpMailer($emailSettings, $newEmail);
//Try to send email.
if (!$email->send()) {
    echo "An error occurred while trying to send the email! Error " . $mail->ErrorInfo;
function setUpMailer($emailSettings, $newEmail)
    try {
        $mail = new PHPMailer();
        //Set true to enable exceptions.
        $mail = new PHPMailer(false);
        //Enable SMTP debugging.
        //$mail->SMTPDebug = 3;
        $mail->SMTPDebug = false;
        //Set PHPMailer to use SMTP.
        //Set SMTP host name. Depends on the email provider you are using.
        $mail->Host = $emailSettings["host"];
        //Set this to true if SMTP host requires authentication to send email.
        $mail->SMTPAuth = true;
        //Provide username and password.
        $mail->Username = $emailSettings["userName"];
        $mail->Password = $emailSettings["password"];
        //If SMTP requires TLS encryption then set it.
        $mail->SMTPSecure = "tls";
        //Set TCP port to connect to:.
        $mail->Port = $emailSettings["port"];
        //Set character encoding.
        $mail->CharSet = 'UTF-8';
        //Sender info.
        $mail->From = $newEmail["email"];
        $mail->FromName = $newEmail["firstName"] . " " . $newEmail["lastName"];
        //Address to which recipient will reply.
        $mail->addReplyTo($newEmail["email"], "Reply");
        //Add recipient address.
        $mail->addAddress($newEmail["recipientEmail"], $newEmail["recipientFirstName"] . " " . $newEmail["recipientLastName"]);
        foreach ($cc as $newEmail["CCEmailAddresses"]) {
        } //Add email attachment.
        foreach ($bcc as $newEmail["BCCEmailAddresses"]) {
        } //Add email attachment.
        //Add email attachments.
        foreach ($attachement as $newEmail["attachements"]) {
            $mail->addAttachment($attachement["attachementPath"], $attachement["attachementName"]);
        } //Add email attachment.
        //Set if the email will contain HTML or not.
        //Set subject.
        $mail->Subject = $newEmail["subject"];
        //Email body with HTML.
        $mail->Body = $newEmail["body"];
        //Email body without HTML.
        $mail->AltBody = $newEmail["altBody"];
        return $mail;
    } catch (Exception $ex) {
        echo "An error occurred while trying to send the email! Error " . $mail->ErrorInfo;

Leave a Reply

Your email address will not be published. Required fields are marked *

The reCAPTCHA verification period has expired. Please reload the page.
The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger