This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Join our live AMA on the Future of Page Builders with Brizy's CEO! Register Now →

How to Send Emails in PHP Using PHPMailer Library

Updated on February 16, 2023

7 Min Read
phpmailer example

Sending emails is an essential part of many web applications. Whether you need to send account activation emails, newsletters, or transactional emails, PHP provides a powerful and flexible way.

PHP’s built-in mail() function has some limitations, including poor handling of attachments, difficulty sending HTML emails, and susceptibility to spam filters. We can use the PHPMailer library instead, which provides a simple and reliable way to send emails in PHP.

In this tutorial, I will show you how to use the PHPMailer library to send emails from your PHP application, including using PHPMailer with localhost and SMTP, as well as more advanced topics like adding attachments and handling errors.

You might also like: How To Host PHP On DigitalOcean

PHPMailer: A PHP mail Alternative

PHPMailer is a third-party PHP library that provides a simple way to send emails in PHP. It offers a range of features that make it a popular alternative to PHP’s built-in mail() function, such as support for HTML emails, attachments, and SMTP authentication.

PHPMailer is easy to set up and use and provides a high level of customization and flexibility, making it a popular choice for developers who need to send emails from their PHP applications. It is also actively maintained and updated, making it a reliable and secure email option.

Here is a quick comparison between PHPMailer and PHP mail:

Feature PHPMailer mail()
Functionality A full-featured email library that allows sending emails with or without SMTP A simple function that allows sending emails via the PHP mail() function
Complexity More complex, but offers more features and options Simpler, with limited options
SMTP Support Supports sending email via SMTP, including authentication and encryption Does not support sending email via SMTP
Attachments Supports sending attachments Does not support attachments
Error Handling Provides detailed error messages and debugging information Provides minimal error information
Security Supports encryption and authentication when sending email via SMTP Does not support encryption or authentication

You might also like: How To Add SSL Certificates To Custom PHP Sites

Advantages of Using PHPMailer

There are many advantages of using PHPMailer over the mail() function to send emails in PHP.

Headers and Dirty Code

Developers write dirty code such as escape characters, encoding, and code for formatting. This is usually done while sending attachments via email in mail(). PHPMailer makes a developer’s life painless, as there is no need to create headers in the same way as in mail() function.

Server Email Subsystem

Mail() function usually needs a local mail server to send emails, whereas PHPMailer uses SMTP.

Also, you should have authentication credentials. This means in case you are using mail() function and you need to change some settings like the SMTP server or the authentication parameters, you need to do it system-wide.

However, with PHPMailer, it is very easy to change server settings or parameters within your PHP script.

Error Sending in Multiple Languages

mail() restricts you from sending emails to very few compatible languages and frameworks. Whereas the PHPMailer library enables you to send error messages in more than 40 languages when message sending fails.

SSL Authentication

This library also supports SMTP protocol and provides authentication over SSL and TLS to ensure encryption and security.

Plain Text Version of Email

mail() can be a good option for sending simple, plain text emails, but it limits you from doing anything more. Adding attachments or sending HTML emails is very difficult with mail(). However, with PHPMailer, you can do that with a single line of code.

Give Your PHP Applications Optimum Web Performance

Host Your PHP Apps With Us & See The Blazing Web Performance Yourself!

How to Install PHPMailer Library?

You can install the PHPMailer library in your PHP project by running the following command in Composer.

composer require phpmailer/phpmailer

Send Emails From Local Web Server

You can send email from a local web server by using the code below.

<?php require_once "vendor/autoload.php"; //PHPMailer Object 
$mail = new PHPMailer; //From email address and name 
$mail->From = "[email protected]"; 
$mail->FromName = "Full Name"; //To address and name 
$mail->addAddress("[email protected]", "Recepient Name");//Recipient name is optional
$mail->addAddress("[email protected]"); //Address to which recipient will reply 
$mail->addReplyTo("[email protected]", "Reply"); //CC and BCC 
$mail->addCC("[email protected]"); 
$mail->addBCC("[email protected]"); //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"; 
}
if(!$mail->send()) 
{ 
echo "Mailer Error: " . $mail->ErrorInfo; 
} 
else 
{ 
echo "Message has been sent successfully"; 
}

Send Emails With Attachments

You can also send emails with attachments using PHPMailer.

<?php 
require_once "vendor/autoload.php"; 
$mail = new PHPMailer; 
$mail->From = "[email protected]"; 
$mail->FromName = "Full Name"; 
$mail->addAddress("[email protected]", "Recipient Name"); //Provide file path and name of the attachments 
$mail->addAttachment("file.txt", "File.txt");    
$mail->addAttachment("images/profile.png"); //Filename is optional 
$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"; 
}

File.txt and images/profile.png have been attached. They are inside the same directory. Attachments can be added by calling addAttachemnt, which is basically an object of PHPMailer. We need to call this object every time as we want to attach more.

How to Use PHPMailer with Localhost?

  • Here is a step-by-step guide on using PHPMailer in localhost:
    Download the PHPMailer library from GitHub. Extract the downloaded zip file and place the PHPMailer folder in your localhost’s root directory.
  • Create a new PHP file in your localhost and include the PHPMailer library:
<
?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';

$mail = new PHPMailer(true);

// code to send email

  • Specify the details of your email, such as the sender’s email address, the recipient’s email address, the subject, the body of the email, etc.
<
try {
    // Server settings
    $mail->SMTPDebug = 2;                      // Enable verbose debug output
    $mail->isSMTP();                                            // Send using SMTP
    $mail->Host       = 'smtp.gmail.com';                    // Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = '[email protected]';                     // SMTP username
    $mail->Password   = 'yourpassword';                               // SMTP password
    $mail->SMTPSecure = 'tls';         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
    $mail->Port       = 587;                                    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above

    // Recipients
    $mail->setFrom('[email protected]', 'Mailer');
    $mail->addAddress('[email protected]', 'Joe User');     // Add a recipient
    $mail->addAddress('[email protected]');               // Name is optional
    $mail->addReplyTo('[email protected]', 'Information');
    $mail->addCC('[email protected]');
    $mail->addBCC('[email protected]');

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

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

    $mail->send();
    echo 'Message has been sent';
} catch

How to Use PHPMailer with SMTP?

When it comes to sending emails using SMTP with PHP, having a reliable hosting solution is crucial. That’s why it’s important to find the best hosting for PHP when developing applications that require sending emails from another host. SMTP requires authentication to ensure that emails are sent securely, much like how someone needs to create an account on Hotmail to send an email. Whether you’re sending a few emails or a large volume of them, having a reliable PHP hosting solution is essential for ensuring that your email sending functionality works as intended.

SMTP is basically a protocol that sends an email request to a mail server and sends it to the destination mail server after verification. Consider the following PHPMailer example to send email using SMTP protocol to a Gmail mail server.

<?php

require_once "vendor/autoload.php";

$mail = new PHPMailer;

//Enable SMTP debugging.

$mail->SMTPDebug = 3;                           

//Set PHPMailer to use SMTP.

$mail->isSMTP();        

//Set SMTP host name                      

$mail->Host = "smtp.gmail.com";

//Set this to true if SMTP host requires authentication to send email

$mail->SMTPAuth = true;                      

//Provide username and password

$mail->Username = "[email protected]";             

$mail->Password = "super_secret_password";                       

//If SMTP requires TLS encryption then set it

$mail->SMTPSecure = "tls";                       

//Set TCP port to connect to

$mail->Port = 587;                    

$mail->From = "[email protected]";

$mail->FromName = "Full Name";

$mail->addAddress("[email protected]", "Recepient Name");

$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";

}

Before sending an email through SMTP, hostname, port number, and encryption are required. Also, you may need a username and password for authentication.

It should be noted here that you cannot send emails to Gmail if two-factor authentication is enabled. It will require some additional configuration.

Advantages of Using Remote SMTP

The biggest advantage of using remote SMTP is that in the PHP mail() function, it is set to other than the local domain name. It will be marked as spam in recipient’s email server.

Let’s consider you own abc.com, and when you send an email, you mention yourself as [email protected] and send it to [email protected]. Then, the Yahoo server will mark it as spam.

Emails Retrieval:

PHPMailer supports POP-before-SMTP verification for sending emails. Hence, it enables you to send emails using SMTP and authenticate using POP. But you can receive emails from mail servers by POP3.

Error Messages:

$mail ->ErrorInfo is used for returning messages in more than 40 languages. To view error messages in any other language, copy the language directory from the PHPMailer source code to the project directory. Consider the following example: the PHPMailer object is set to the Russian Language.

$mail->setLanguage("ru");

Host PHP Websites with Ease [Starts at $10 Credit]

  • Free Staging
  • Free backup
  • PHP 8.0
  • Unlimited Websites

TRY NOW

Summary

With PHPMailer, you can ensure that your emails are delivered smoothly and efficiently without the hassle of managing email sending on your own. After reading this article, you can get up and running with PHPMailer and start sending emails from your PHP application.

With its intuitive and easy-to-use API, developers can quickly and easily configure SMTP settings, set email properties, add attachments, send HTML emails, and handle errors and exceptions.

Q: What does PHPMailer do?

A: PHPMailer is a library for sending emails in PHP. It provides a simple and flexible way to send emails from a PHP script. It allows you to send plain text, HTML emails, and emails with attachments.

Using PHPMailer, you can avoid writing complex and error-prone code to send emails. It also provides many additional features, such as error handling and debugging.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Inshal Ali

Inshal is a Content Marketer at Cloudways. With background in computer science, skill of content and a whole lot of creativity, he helps business reach the sky and go beyond through content that speaks the language of their customers. Apart from work, you will see him mostly in some online games or on a football field.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now