loading...
Cover image for PHPMailer: How to send Emails in PHP

PHPMailer: How to send Emails in PHP

ijsucceed profile image Jeremiah Ikwuje ・4 min read

In this comprehensive guide, you’ll learn how to send emails in PHP with PHPMailer.

Why not mail()?

PHP mail() hardly get the job done.

I don’t feel a need to go a distance to why the mail() is bad.

You’re always going to be building web apps that have something to do with emails. And you don’t want even a single thing to fail while sleeping.

Think PHPMailer

PHPMailer has an object-oriented interface, whereas the mail() is not object-oriented.

PHPMailer features an integrated SMTP support. This means you can send emails without a local mail server. This is brilliant on a naked cloud hosting that does not support emails.

Further painless reasons to use PHPMailer includes:

  1. Send attachments, including inline and HTML based emails

  2. Validates email addresses automatically

  3. Protect against header injection attacks

  4. Print error messages in several languages

  5. Send without a local mail server

  6. and much more!

Installing PHPMailer

Are you still ignoring composer? Don’t, please.

The recommended way to install PHPMailer is via composer. Just add this line to your composer.json file:

phpmailer/phpmailer": "~6.1"
Enter fullscreen mode Exit fullscreen mode

or simply run:

composer require phpmailer/phpmailer
Enter fullscreen mode Exit fullscreen mode

This will add the PHPMailer package inside the vendor folder generated by Composer.

You’re now going to see several examples of sending emails with PHPMailer.

Sending emails using PHPMailer on a local server

<?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;

require_once "vendor/autoload.php";

// PHPMailer Object
$mail = new PHPMailer();

// From email address and name
$mail->From = "jeremiah@tolearn.com.ng"; // replace to your own domain
$mail->FromName = "Jeremiah Succeed"; // replace to your own name

// To address and name
$mail->addAddress("recipent1@example.com", "Recipent Name");
$mail->addAddress("recepient1@example.com"); // Recipient name is optional

// Address to which recipient will reply
$mail->addReplyTo("reply@yourdomain.com", "Reply");

// CC and BCC
$mail->addCC("cc@example.com");
$mail->addBCC("bcc@example.com");

// Send HTML or Plain Text email
$mail->isHTML(true);

$mail->Subject = "Subject Text";
$mail->Body = "<i>Mail body in HTML</i>";
$mail->AltBody = "This is the plain text version of the email content";

if(!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} 
else {
    echo "Message has been sent successfully";
}
Enter fullscreen mode Exit fullscreen mode

While the code above sends the email to the recipent, try to avoid it. Most of your emails will go straight to the recipent SPAM folder. And am sure it's not something you want.

Use STMP.

Sending emails with STMP

I mentioned above that PHPMailer has an integrated STMP support which enables you to send email without needing a local mail server.

SMTP is a protocol used by mail clients to send an email request to a mail server. And Once the mail server verifies that email, it sends it to the recipient mail server.

You can send an email with an external email host like Gmail. For example with a Gmail account, you can send an email from your application using your Gmail username and password.

This example code sends emails without a local mail server. A strong reason to use PHPMailer.

<?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';

// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;  // Enable verbose debug output
    $mail->isSMTP();     // Send using SMTP
    $mail->Host       = 'stmp.gmail.com'; // Set the SMTP server to send through
    $mail->SMTPAuth   = true;   // Enable SMTP authentication
    $mail->Username   = 'username@gmail.com';     // SMTP username
    $mail->Password   = 'Gmail 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

    // From email address and name
    $mail->setFrom('jeremiah@tolearn.com.ng', 'Jeremiah Succceed');

    // To email addresss
    $mail->addAddress('recipent1@example.com');   // Add a recipient
    $mail->addReplyTo('reply@example.com', 'Reply'); // Recipent reply address
    $mail->addCC('cc@example.com');
    $mail->addBCC('bcc@example.com');

    // Content
    $mail->isHTML(true);  // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
Enter fullscreen mode Exit fullscreen mode

I used Gmail STMP settings in the code above. Simply replace the $mail->username and $mail->password with your Gmail address and password.

You can use other STMP hosts like MailGun, Postmark, Sendinblue, elasticmail, e.t.c.

Send an email with Attachment

To send an attachment to the recipient, simply add the below code before the $mail->send()

// Attachments
$mail->addAttachment('/path/to/file.mp3');         // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

...
$mail->send();
Enter fullscreen mode Exit fullscreen mode

Send email to multiple addresses

To send to multiple emails, simply addAddress('email') as much you want to.

$mail->addAddress('recipent2@gmail.com');   // Add a recipient
$mail->addAddress('recipent3@gmail.com');   // Add a recipient
$mail->addAddress('recipent4@gmail.com');   // Add a recipient
Enter fullscreen mode Exit fullscreen mode

Conclusion

You just learnt how to send emails in PHP using PHPMailer.

They are other premium email API services you can use to speedily send emails in PHP. However, sometimes just doing things with PHPMailer is enough - considering it free to use.

You can learn about PHPMailer APIs in the official documentation.

Do you enjoy PHPMailer? Or do you encounter any difficulties? Let me know in the comments!

Discussion

pic
Editor guide