Skip to content

How to Send Email Attachments via PHP

When sending an email, it is often necessary to include attachments as well. In this tutorial, we will show you how to send email attachments with PHP easily.

Just follow the steps below.

Using the PHPMailer Script

PHPMailer is the most straightforward option for sending attachments with PHP.

To use it, you need to follow the steps below:

Installing via Composer

As a first step, you need to install PHPMailer using Composer, which is the recommended method for modern PHP projects:

bash
composer require phpmailer/phpmailer

Include the Main Script File

The next step is including the Composer autoloader in your script:

php include the main script file

php
require 'vendor/autoload.php';

Sending Emails

Finally, you can see that sending emails with attachments becomes straightforward. To be more precise, let’s consider an example:

send email with attachment with phpmailer

php
<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$bodytext = 'This is the email body text.';

try {
    $mail = new PHPMailer(true);
    // Server settings
    $mail->isSMTP();
    $mail->Host       = 'smtp.example.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = '[email protected]';
    $mail->Password   = 'your_password';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;

    // Recipients
    $mail->setFrom('[email protected]', 'Your Name');
    $mail->addAddress('[email protected]');

    // Content
    $mail->Subject = 'Message Subject';
    $mail->Body    = $bodytext;

    // Attachment
    $file_to_attach = 'PATH_OF_YOUR_FILE_HERE';
    $mail->addAttachment($file_to_attach, 'NameOfFile.pdf');

    $mail->send();
    echo 'Message sent successfully.';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

?>

So, we can state that PHPMailer is an easy and efficient way to send attachments with PHP.

There is an alternative means such as PHP mail() function, but we do not recommend using it. The reason is that it lacks built-in support for MIME boundaries and requires extensive boilerplate code to handle attachments correctly.

Describing PHPMailer

PHPMailer is considered a classic email sending library for PHP. It supports various means to send email messages. Among them are qmail, mail(), Sendmail, and so on. Moreover, it includes a range of additional advanced features such as support of TLS and SSL protocols, SMTP authentication, HTML content along with plain text, and more.

Dual-run preview — compare with live Symfony routes.