How To Attach Multiple Files in PHPMailer Email Using PHP

attach multiple files in PHPMailer
attach multiple files in PHPMailer

Share this Article!

Are you looking to enhance user interaction on your website by seamlessly learning How To Attach Multiple Files in PHPMailer Email Using PHP? In today’s digital world, web applications often require the ability to allow users to attach multiple files when submitting forms or sending emails.

PHP, being a versatile server-side scripting language, is commonly used for such tasks. PHPMailer, a popular email library, offers a seamless way to attach multiple files to emails. In this comprehensive guide, we will walk you through the process of how to Attach Multiple Files in PHPMailer Email using PHP.

You’re in the right place. In this comprehensive guide, we will explore the ins and outs of using PHP Mailer to achieve this functionality. From setting up PHP Mailer to handling form data and sending emails, we’ve got you covered.

What is PHP Mailer?

Before we dive into the details, let’s briefly introduce PHP Mailer. PHP Mailer is a robust PHP library that simplifies the process of sending emails through PHP scripts. It offers an intuitive and feature-rich interface for sending plain text and HTML emails, complete with attachments and more.

Steps – Attach Multiple Files in PHPMailer

Let’s start with a detailed outline that will guide us to Attach Multiple Files in PHPMailer Email through this extensive guide. Here are the important steps to Attach Multiple Files in PHPMailer on HTML form submission:

  1. Download and install PHP Mailer from GitHub
  2. Setup your HTML Contact Form
  3. Include PHP Mailer in your HTML code
  4. Configure PHP Mailer
  5. Adding multiple attachments to PHPMailer
  6. Process form data to send email
  7. Compose the Email
  8. Handle Success and Error messages
  9. Send the Email

Video Tutorial – Attach Multiple Files in PHPMailer

Now that we have our roadmap, let’s explore each section in detail to Attach Multiple Files in PHPMailer.

How to Send HTML Form to Email Using PHP Mailer

Sending HTML forms via email is a seamless process when you have PHP Mailer at your disposal. Here’s a step-by-step guide to achieving, how to attach multiple files in PHPMailer:


Before diving into implementation, ensure that you have the following prerequisites in place:

  1. A Web Server with PHP Support: You’ll need a web server, such as Apache or Google, with PHP support to run your PHP Mailer script.
  2. Email Server Access: Ensure you have access to an email server or SMTP server to send emails, such as Gmail.
  3. Basic HTML and PHP Knowledge: Familiarize yourself with HTML to create the form and PHP to process it.

Getting Started

Let’s start by downloading PHP Mailer and setting up our HTML form to Attach Multiple Files in PHPMailer email using PHP:

1. Download and install PHP Mailer

Begin by downloading the PHP Mailer library. You can obtain it from the official GitHub repository or use Composer if you prefer package management.

To Download the PHP Mailer manually from the GitHub library Click Here!

If you want to install the PHPMailer using Composer. First of all, simply install the Composer Setup on your computer and run the following command in your terminal:

composer require phpmailer/phpmailer

Alternatively, if you’re not using Composer, you can download PHPMailer as a zip file, and then copy the contents of the PHPMailer folder into one of the include_path directories specified in your PHP configuration and load each class file manually:

2. Set Up Your HTML Form

Create an HTML form on your website where users can submit their information. Ensure that your form fields have appropriate name attributes.

HTML Form Source Code

I have created a simple HTML form to send web form data to email using PHPMailer. I will collect this form data from the user and send it to my email address using PHPMailer.

<!DOCTYPE html>
<html lang="en">

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
    @import url(,400,300,600);

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;

    body {
      font-weight: 300;
      font-size: 12px;
      line-height: 30px;
      color: #272727;
      background: rgb(25, 199, 155);

    .container {
      max-width: 400px;
      width: 100%;
      margin: 0 auto;
      position: relative;

    #contact input {
      font: 400 12px/16px;
      width: 100%;
      border: 1px solid #CCC;
      background: #FFF;
      margin: 10 5px;
      padding: 10px;

    h1 {
      margin-bottom: 30px;
      font-size: 30px;

    #contact {
      background: #F9F9F9;
      padding: 25px;
      margin: 50px 0;

    fieldset {
      border: medium none !important;
      margin: 0 0 10px;
      min-width: 100%;
      padding: 0;
      width: 100%;

    textarea {
      height: 100px;
      max-width: 100%;
      resize: none;
      width: 100%;

    button {
      cursor: pointer;
      width: 100%;
      border: none;
      background: rgb(17, 146, 60);
      color: #FFF;
      margin: 0 0 5px;
      padding: 10px;
      font-size: 20px;

    button:hover {
      background-color: rgb(15, 95, 42);

  <div class="container">
    <form id="contact" action="mail.php" method="post" enctype="multipart/form-data">
      <h1>Contact Form</h1>

        <input placeholder="Your name" name="name" type="text" tabindex="1" autofocus>
        <input placeholder="Your Email Address" name="email" type="email" tabindex="2">
        <textarea name="message" placeholder="Type your Message Details Here..." tabindex="5"> 

       <!-- Multiple file attachment -->
        <label for="file">
          <h3> Upload your documents:</h3>
        <input name="file[]" multiple="multiple" type="file">

        <button type="submit" name="send" id="contact-submit">Submit Now</button>


HTML Form Output

The HTML form will look like as:

attach multiple files in PHPMailer using php
Attach multiple files in PHPMailer using PHP

3. Include PHP Mailer

In your PHP script, include the PHP Mailer library using require or require_once. as shown in the following script:

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

//required files
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';

4. Configure PHP Mailer

Set up PHP Mailer with your email server details, including the SMTP host, username, password, and port. Make sure to use valid credentials and a secure connection.

If you are using a Gmail SMTP server, first of all, login to your Gmail ID, turn on 2-step authentication and generate an App Password.

To generate an App Password in your Gmail account follow this link.

//Server settings
    $mail = new PHPMailer(true);
    $mail->isSMTP();                                   //Send using SMTP
    $mail->Host       = '';    //Set the SMTP server to send through
    $mail->SMTPAuth   = true;           //Enable SMTP authentication
    $mail->Username   = 'your email';   //SMTP username
    $mail->Password   = 'app gererated password';   //SMTP password
    $mail->SMTPSecure = 'ssl';            //Enable implicit SSL encryption
    $mail->Port       = 465;      

5. Process Form Data

In your PHP script, retrieve the form data submitted by the user using $_POST or $_GET, depending on your form’s method attribute. In this tutorial, we have received the following form data from the user:

$_POST["send"];       //  for submit button
$_POST["email"]       // user email
$_POST["name"]        // user name
$_POST["message"]     // email message

6. Attach Multiple Files in PHPMailer

HTML Form Setup

To receive multiple file attachments, you first need an HTML form that allows users to upload files. Ensure the form’s enctype attribute is set to “multipart/form-data” for proper file handling.

Handling File Uploads in PHP

In your PHP script, use the $_FILES[‘file’] superglobal to access the uploaded files. Loop through the files array to handle each attachment individually.

Now comes the crucial part. Using PHPMailer, you can add each uploaded file as an attachment to your email. PHPMailer provides a simple and efficient way to do this.

//For multiple file attachments

  for ($i = 0; $i < count($_FILES['file']['tmp_name']); $i++) {
     $mail->addAttachment($_FILES['file']['tmp_name'][$i], $_FILES['file']['name'][$i] );  

6. Compose the Email

Use PHP Mailer to compose your email. You can format it as plain text or HTML, depending on your preference. Here is the complete PHPMailer source code to Attach Multiple Files in PHPMailer:

PHPMailer Complete Source Code

Copy the below source code and change the data according to your preferences:


//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\Exception;

//required files
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';

//Create an instance; passing `true` enables exceptions
if (isset($_POST["send"])) {

  $mail = new PHPMailer(true);

    //Server settings
    $mail->isSMTP();                              //Send using SMTP
    $mail->Host       = '';       //Set the SMTP server to send through
    $mail->SMTPAuth   = true;             //Enable SMTP authentication
    $mail->Username   = 'your email address';   //SMTP write your email
    $mail->Password   = 'app password';      //SMTP password
    $mail->SMTPSecure = 'ssl';            //Enable implicit SSL encryption
    $mail->Port       = 465;                                    

    $mail->setFrom( $_POST["email"], $_POST["name"]); // Sender Email and name
    $mail->addAddress('[email protected]');     //Add a recipient email  
    $mail->addReplyTo($_POST["email"], $_POST["name"]); // reply to sender email
    //multiple file attachment
  for ($i = 0; $i < count($_FILES['file']['tmp_name']); $i++) {
     $mail->addAttachment($_FILES['file']['tmp_name'][$i], $_FILES['file']['name'][$i] ); 

    $mail->isHTML(true);               //Set email format to HTML
    $mail->Subject = 'Received New Message From: '. $_POST["name"];   // email subject headings
    $mail->Body    = $_POST["message"]; //email message
    // Success sent message alert
     alert('Message was sent successfully!');
     document.location.href = 'index.php';

7. Handle Success and Error messages

Implement error handling to deal with scenarios where the email-sending process might fail. Display a success message to the user upon successful submission.

8. Send the Email

Use the send method to send the email. Ensure to implement error handling to deal with scenarios where the email-sending process might fail.

if ($mail->send()) {
    echo 'Email sent successfully.';
} else {
    echo 'Email could not be sent. Error: ' . $mail->ErrorInfo;

9. Testing Your Setup

After implementing the above steps, thoroughly test your setup. Submit test data through your HTML form to ensure that emails are being sent correctly to the specified email address.


Incorporating multiple file attachments in PHPMailer emails for form submissions can greatly enhance your web application’s functionality and user experience. With the right setup and practices, you can streamline the process of collecting essential files from users and ensure smooth communication between your website and its visitors.

Now that you’ve learned how to attach multiple files using PHPMailer, you can provide an improved user experience while efficiently collecting data.

Now, let’s address some frequently asked questions (FAQs) related to PHP Mailer and email functionality.


Q1: Can I attach any file type with PHPMailer?

Yes, PHPMailer allows you to attach various file types, including documents, images, and more. However, it’s crucial to implement proper validation to ensure security and data integrity.

Q2: What if an uploaded file exceeds the size limit?

You can set file size limits in your PHP script to reject files that exceed a specified size. Additionally, you can provide feedback to users on the maximum allowable file size.

Q3: How can I prevent malicious file uploads?

To prevent malicious file uploads, validate file types, and use secure file handling practices. You can also consider using antivirus software to scan uploaded files.

Q4: Is PHPMailer suitable for large file attachments?

While PHPMailer can handle file attachments, it’s advisable to use dedicated file-sharing services for very large files. PHPMailer is more suitable for smaller to moderately sized attachments.

Q5: What other features can I explore with PHPMailer?

PHPMailer offers various features like HTML email support, CC and BCC recipients, and email templates. You can explore these features to enhance your email communication.

Share this Article!

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe Our YouTube Channel!

Follow for Latest Updates