DEV Community

Cover image for How To Attach Multiple Files in PHPMailer Email Using PHP
HMA WebDesign
HMA WebDesign

Posted on

How To Attach Multiple Files in PHPMailer Email Using PHP

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 – Send HTML Form via PHP Mailer

Let’s start with a detailed outline that will guide us to Send HTML Form via PHP Mailer through this extensive guide. Here are the important steps to Send an HTML Form via PHP Mailer 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. Process form data to send email
  6. Compose the Email
  7. Handle Success and Error messages
  8. Send the Email

Video Tutorial – Send HTML Form via PHP Mailer

Now that we have our roadmap, let’s explore each section in detail to Send HTML Forms via PHP Mailer.
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.

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

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.

Email Server Access: Ensure you have access to an email server or SMTP server to send emails, such as Gmail.
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 Send HTML Form via PHP Mailer:

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.

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.

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.

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

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    @import url(https://fonts.googleapis.com/css?family=Open+Sans:400italic,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);
    }
  </style>
</head>

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

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

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

      <fieldset>
        <button type="submit" name="send" id="contact-submit">Submit Now</button>
      </fieldset>
    </form>
  </div>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

PHPMailer Source Code

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

<?php

//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       = 'smtp.gmail.com';       //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;                                    

    //Recipients
    $mail->setFrom( $_POST["email"], $_POST["name"]); // Sender Email and name
    $mail->addAddress('example@gmail.com');     //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] ); 
  }

    //Content
    $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
    $mail->send();
    echo
    " 
    <script> 
     alert('Message was sent successfully!');
     document.location.href = 'index.php';
    </script>
    ";
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

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.

Top comments (0)