About
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.
Code:
<?php //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" => "smtp.office365.com", //Depends on your email provider. For example, outlook: "smtp.office365.com", gmail: "smtp.gmail.com", ...; "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; } ///////////////////////////////////////////////////////////////////////////////////////////////// //Functions////////////////////////////////////////////////////////////////////////////////////// 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. $mail->isSMTP(); //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"]); //CC foreach ($cc as $newEmail["CCEmailAddresses"]) { $mail->addCC($cc); } //Add email attachment. //BCC foreach ($bcc as $newEmail["BCCEmailAddresses"]) { $mail->addBCC($bcc); } //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. $mail->isHTML(true); //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; } } //////////////////////////////////////////////////////////////////////////////////////////////////