How to add attachment in email in PHP

Updated: January 12, 2024 By: Guest Contributor Post a comment

Introduction

Adding attachments to emails in PHP can enhance communication by allowing you to send images, documents, and other forms of media along with your messages. Whether you’re managing automated reports, user-generated content, or simply sharing files, utilizing PHP’s email capabilities with attachments is a powerful feature.

PHP, being a server-side scripting language, offers built-in functions and extensions to send emails. The mail() function can prove adequate for sending simple emails. However, for attachments, we’ll need a multipart message body conforming to the MIME (Multipurpose Internet Mail Extensions) standards. This can be a bit trickier. In this tutorial, we utilize the PHPMailer library, which greatly simplifies the task of sending emails with attachments.

Getting Started with PHPMailer

To start sending emails with attachments using PHPMailer, you’ll need to have PHPMailer installed. You can either download PHPMailer from its GitHub repository or install it via Composer:

composer require phpmailer/phpmailer

This will add PHPMailer to your project’s vendor directory, and you can use it by requiring the autoload script.

Step-by-Step Guide to Sending an Attachment Email

Step 1: Load PHPMailer

<?php
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer(true);
try {
    // Email server settings
}
?>

Step 2: Configure SMTP Settings

Most emails are sent using an SMTP server. You’ll need to provide server details and authentication to PHPMailer:

$mail->isSMTP();
$mail->Host = 'your.smtp.server';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'tls' or 'ssl';
$mail->Port = 587 or 465; // Use 587 for TLS, 465 for SSL

Step 3: Compose the Email

Set the sender, recipient, subject, and the body of the email:

$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient's Name');
$mail->Subject = 'Here is your subject';
$mail->Body    = 'This is the email body';
$mail->isHTML(true); // Set email format to HTML

Step 4: Attach the File

To attach files, use the addAttachment() function:

$mail->addAttachment('/path/to/file','optional-filename');

Complete the path to the file and, if desired, provide an alternative filename for the attachment.

Step 5: Handling Errors and Sending the Email

Catch exceptions and send the email, handling any potential errors:

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

Testing Your Setup

To ensure that your email sending capability works with an attachment, you’ll want to perform a test. Replace placeholder values with actual server details and file paths and execute your PHP script, either from the command line or by loading it on a server.

Additional Tips and Considerations

  • File Size Limits: Be aware of the maximum size for attachments allowed by your SMTP server to prevent errors.
  • Security: Always verify user-uploaded files to prevent compromising the system.
  • Email Headers: If you opt to use PHP’s traditional mail() function, be sure to correctly format headers for multipart emails.
  • Testing in Different Email Clients: Test how emails with attachments sent through your PHP script appear in various email clients to ensure compatibility.

Conclusion

Learning how to send emails with attachments in PHP can extend the functionality of your applications. While the underlying protocols and standards are complex, libraries like PHPMailer abstract away much of the difficulty, allowing you to send powerful and feature-rich emails.

Note: The above tutorial assumes basic knowledge of PHP and its configuration. It’s also essential to verify that your hosting environment allows for email sending and that necessary ports (like 587 and 465 for SMTP) are not blocked by your hosting provider’s firewall.