PHPMailer: how to send emails easily

PHPMailer is a framework which regulates email transfer through PHP. PHPMailer is mainly used for contact forms on websites, but it also works when sending private emails.

Hosted Exchange with IONOS

The prefect solution for your business! Get the world’s leading email and calendar solution together with secure hosting from a single source!

25 GB email
Free domain
24/7 support

What is PHPMailer?

PHPMailer is a mail extension provided by a community for PHP. The probability that emails sent with PHPMailer ending up in your spam folder is much lower when compared to the mail command, which is implemented in PHP from the beginning. This is because mails which are written with PHPMailer are sent using SMTP. SMTP stands for Simple Mail Transfer Protocol and it is used to transfer emails over the Internet.

What do you use PHPMailer for?

PHPMailer is a bit more tedious to use when compared to other email providers or integrated mail programs on your computer, which might leave you wondering why people choose to use PHPMailer. The PHP framework simplifies creating automated responses, such as those needed for a web store. Additionally, PHPMailer is also suitable for contact forms on websites.

Requirements for PHPMailer

You need an SMTP server to use PHPMailer. It is your decision whether you use the mail server from a provider or set up your own server. Composer is a package manager for PHP which is recommended to install the PHP extension.

Tip

Mastering the PHP basics is another important requirement for using PHPMailer. Our PHP beginner’s tutorial may be useful if you are having trouble with PHP basics!

Installing PHPMailer: step-by-step instructions

Step 1: Download current PHPMailer version

Download the latest version of PHPMailer. You can do this with the package manager or manually from GitHub.

Option 1: Download through Composer

Use the following command if you have installed the package manager Composer:

composer require phpmailer/phpmailer

Important: If you have installed PHPMailer with Composer, you must include Composer in your PHP code to send mails.

The following line of code is suitable:

require_once "vendor/autoload.php";

The keyword "require_once" ensures the composer is only included once. Otherwise, this may lead to program errors. The installation using Composer is then completed.

Option 2: Download directly from GitHub

The PHPMailer source files can also be downloaded manually by selecting ``Clone or download´´ in the corresponding GitHub repository.

Step 2: Unzip files

You have to open the ZIP files if you have downloaded PHPMailer’s source code manually. Select the location where you want to install PHPMailer and include PHPMailer in your script. Use the following lines of code, assuming you have unpacked the PHPMailer files in a folder called PHPMailer:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
/* Class for handling exceptions and errors */
require 'C:\PHPMailer\src\Exception.php';
/* PHPMailer class */
require 'C:\PHPMailer\src\PHPMailer.php';
/* SMTP class needed to connect to an SMTP server */.
require 'C:\PHPMailer\src\SMTP.php';
$email = new PHPMailer(TRUE);

Sending emails with PHPMailer: step-by-step instructions

Step 1: Include namespaces

Ensure the namespaces are correct to access PHPMailer. Use statements are required for this, so your code should contain the following lines:

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

You can access the individual classes by including the name after the last slash.

Step 2: Catch errors

While PHPMailer is a very reliable way to send emails, errors can occur from time to time. It is recommended to include a try-catch statement in an email dispatch to prevent sensitive data from your mail server being sent to users as an error message:

try {
    // Try to create a new instance of PHPMailer class
    $mail = new PHPMailer (true);
// (...)
} catch (Exception $e) {
        echo "Mailer Error: ".$mail->ErrorInfo;
}

Step 3: Authentication with SMTP

You must authenticate yourself with SMTP to use PHPMailer. Enter the address of your mail server next to the appropriate protocol (either TLS/SSL or SMTP) and include the port with your username and password. The protocol and port which you use depend on your mail provider. The respective server data can be retrieved from the mail providers’ websites.

$mail->isSMTP();
$mail->SMTPAuth = true;
// Personal data
$mail->host = "smtp.domain.com";
$mail->Port = "587";
$mail->username = "name.surname@domain.com";
$mail->password = "testpassword4321";
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;

Step 4: State the recipient of the email

Now you can state the recipients of your email in the script.

// Sender
$mail->setFrom('info@example.com', 'name');
// Recipient, the name can also be stated
$mail->addAddress('info@example.com', 'name');
// Copy
$mail->addCC('info@example.com');
// Blind copy
$mail->addBCC('info@example.com', 'name');

Step 5: Add mail content

Don’t forget the content of your email! This content will usually consist of a subject and a text, which can be specified as both HTML and non-HTML versions. It’s important to note that older software may not be able to handle the current HTML5 standard, so it may be worthwhile to create your email using HTML.

You can also send attachments easily with PHPMailer using the addAttachment function. Images, music, documents, videos, and GIFs can also be sent with PHPMailer. You can also rename your attachments with an optional second parameter which are transferred to the function.

$mail->isHTML(true);
// Subject
$mail->Subject = 'The subject of your mail';
// HTML content
$mail->Body = 'The mail text as HTML content. <b>bold</b> elements are allowed.';
$mail->AltBody = 'The text as a simple text element';
// Add attachment
$mail-> addAttachment("/home/user/Desktop/sampleimage.png", "sampleimage.png");

Step 6: Use the correct character encoding

Due to the various accent letters in other languages, it may be a good idea to enable UTF-8 in PHPMailer to prevent display errors, especially when using various attachments. Add the following lines of code to your PHP script for this:

$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64';

Step 7: Send email

Finally, you just need to send your email. Use the command:

$mail-> send();

It is a good idea to place all of the code shown in this send request in the try statement block of your script to catch any errors.

An example of code to send emails

All the code required to send an email with an image attached to a recipient of your choice using PHPMailer is summarized as follows:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once "vendor/autoload.php";
try {
        // Create instance of PHPMailer class
        $mail = new PHPMailer($debug);
        if ($debug) {
                // issue a detailed log
                $mail->SMTPDebug = PHPMailer\PHPMailer\SMTP::DEBUG_SERVER; }
        }
        // Authentication with SMTP
        $mail-> isSMTP();
        $mail->SMTPAuth = true;
        // Login
        $mail->host = "smtp.domain.com";
        $mail->Port = "587";
        $mail->username = "name.surname@domain.com";
        $mail->password = "testpassword4321";
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail-> addAttachment("/home/user/Desktop/sampleimage.png", "sampleimage.png");
     $mail->CharSet = 'UTF-8';
     $mail->Encoding = 'base64';
        $mail->isHTML(true);
        $mail->Subject = 'The subject of your mail';
     $mail->Body = 'The mail text in HTML content. <b>bold</b> elements are allowed.';
     $mail->AltBody = 'The text as a simple text element';
        $mail->send();
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: ".$mail->ErrorInfo;
}

Email hosting services tailored to your needs

Increase your credibility with an email address that matches your business!

Ad-free email
Spam filter
Secure
We use cookies on our website to provide you with the best possible user experience. By continuing to use our website or services, you agree to their use. More Information.