Send Email with Multiple Attachments using PHP with Phpmailer
Sending email functionality is very useful for the dynamic web application. In this tutorial, we will explain to you how to sending an email with multiple attachments using phpmailer library. We will be using the PHPMailer. The attachment files are chosen and attached to the email via an HTML form. You can also download source code of the live example.
So let’s implement the Send Email with Multiple Attachments using PHP, Ajax & MySQL. look files structure:
- send-email-with-multiple-attachments-using-php
- library
- assets
- css
- style.css
- css
- templates
- header.php
- footer.php
- index.php
- action.php
Step 1: Create a HTML Form
Make a PHP file to send mail with multiple attachments
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
<?php include('templates/header.php'); ?> <section class="showcase"> <div class="container"> <div class="pb-2 mt-4 mb-2 border-bottom"> <h2>Send Email with Multiple Attachments using PHP with Phpmailer</h2> </div> <div class="row"> <div class="col-sm-12"><span id="success-msg"></span></div> </div> <form method="POST" class="sending-email-frm" id="sending-email-frm" enctype="multipart/form-data"> <div class="row"> <div class="col-sm-12"> <div class="row"> <div class="col-sm-8 offset-md-2"> <form method="post" data-form-title="Send Email multiple attachment"> <div class="form-group"> <input type="text" class="form-control imput-mail-name" name="name" required="" placeholder="Name*" data-form-field="Name"> </div> <div class="form-group"> <input type="email" class="form-control imput-mail-email" name="email" required="" placeholder="Email*" data-form-field="Email"> </div> <div class="form-group"> <input type="text" class="form-control imput-mail-subject" name="subject" required="" placeholder="Subject*" data-form-field="Subject"> </div> <div class="form-group"> <textarea class="form-control imput-mail-message" name="message" placeholder="Message*" rows="7" data-form-field="Message" required=""></textarea> </div> <div class="form-group"> <input type="file" class="form-control imput-mail-attachment" name="attachment[]" required="" data-form-field="attachment" multiple="multiple"> </div> <div> <button type="button" class="btn btn-md btn-info float-right" id="sending-mail">SEND</button> </div> </form> </div> </div> </div> </div> </form> </div> </section> <?php include('templates/footer.php'); ?> <script type="text/javascript"> jQuery(document).on('click', 'button#sending-mail', function() { jQuery.ajax({ type:'POST', url:'action.php', data: new FormData(jQuery("form#sending-email-frm")[0]), contentType: false, cache: false, processData:false, dataType:'json', beforeSend: function () { jQuery('button#sending-mail').button('Loding..'); }, complete: function () { jQuery('button#sending-mail').button('reset'); setTimeout(function () { jQuery("form#sending-email-frm")[0].reset(); }, 2000); }, success: function (json) { $('.text-danger').remove(); if (json['error']) { jQuery('span#success-msg').html(''); for (i in json['error']) { var element = $('.imput-mail-' + i.replace('_', '-')); if ($(element).parent().hasClass('input-group')) { $(element).parent().after('<div class="text-danger" style="font-size: 14px;">' + json['error'][i] + '</div>'); } else { $(element).after('<div class="text-danger" style="font-size: 14px;">' + json['error'][i] + '</div>'); } } } else { jQuery('span#success-msg').html('<div class="alert alert-success">You have successfully subscribed to the newsletter</div>'); } }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); </script> |
Step 2: Posting Form Data via jQuery AJAX
The following JavaScript code handles the sending email with attachment request using jQuery and Ajax
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
jQuery(document).on('click', 'button#sending-mail', function() { jQuery.ajax({ type:'POST', url:'action.php', data: new FormData(jQuery("form#sending-email-frm")[0]), contentType: false, cache: false, processData:false, dataType:'json', beforeSend: function () { jQuery('button#sending-mail').button('Loding..'); }, complete: function () { jQuery('button#sending-mail').button('reset'); setTimeout(function () { jQuery("form#sending-email-frm")[0].reset(); }, 2000); }, success: function (json) { $('.text-danger').remove(); if (json['error']) { jQuery('span#success-msg').html(''); for (i in json['error']) { var element = $('.imput-mail-' + i.replace('_', '-')); if ($(element).parent().hasClass('input-group')) { $(element).parent().after('<div class="text-danger" style="font-size: 14px;">' + json['error'][i] + '</div>'); } else { $(element).after('<div class="text-danger" style="font-size: 14px;">' + json['error'][i] + '</div>'); } } } else { jQuery('span#success-msg').html('<div class="alert alert-success">You have successfully subscribed to the newsletter</div>'); } }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); |
Step 3: Create a file named action.php
Create the mail objects for the PHPMailer class. Send Email with Multiple Attachment using Custom PHP Function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
<?php $json = array(); $post = $_POST; if(empty(trim($post["name"]))) { $json['error']['name'] = 'Please enter your name'; } if(empty(trim($post["email"]))) { $json['error']['email'] = 'Please enter your email address'; } if (validateEmailAddress($post["email"]) == FALSE) { $json['error']['email'] = 'Please enter valid email address'; } if(empty(trim($post["subject"]))) { $json['error']['subject'] = 'Please enter subject'; } if(empty(trim($post["message"]))) { $json['error']['message'] = 'Please enter message'; } if(empty($json['error'])) { // include phpmailer library require('library/class.phpmailer.php'); //SMTP username $smtpUserName = 'xxxxx@gmail.com'; // Gmail SMTP password $smtpPassword = 'xxxxx'; // SMTP server name $smtpHostName = 'smtp.gmail.com'; $recipientEmail = 'info@codersmag.com'; $mail = new PHPMailer(); $mail->IsSMTP(); $mail->SMTPDebug = 0; $mail->SMTPAuth = TRUE; $mail->SMTPSecure = "ssl"; $mail->Port = 465; $mail->Username = $smtpUserName; $mail->Password = $smtpPassword; $mail->Host = $smtpHostName; $mail->Mailer = "smtp"; $mail->SetFrom($post["email"], $post["name"]); $mail->AddReplyTo($post["email"], $post["name"]); $mail->AddAddress($recipientEmail); $mail->Subject = $post["subject"]; $mail->WordWrap = 80; $mail->MsgHTML($post["message"]); foreach ($_FILES["attachment"]["name"] as $key => $element) { $mail->AddAttachment( $_FILES["attachment"]["tmp_name"][$key], $_FILES["attachment"]["name"][$key] ); } $mail->IsHTML(true); if(!$mail->Send()) { $json['stats'] = 0; $json['message'] = "Problem in Sending Mail."; } else { $json['stats'] = 1; $json['message'] = 'Mail Sent Successfully'; } } header('Content-Type: application/json'); echo json_encode($json); // check email validation function validateEmailAddress($email) { return preg_match('/^[^\@]+@.*.[a-z]{2,15}$/i', $email)?TRUE:FALSE; } ?> |
Step 4: Create header (header.php)
This view contains the header section of the webpage. The Bootstrap library is used to provide a better UI, so, include it in the header section.
Located at the top of a website, the header typically contains elements that include a company’s logo, website navigation, and contact information.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<!DOCTYPE html> <html lang="en"> <head> <link rel="canonical" href="https://www.codersmag.com/" /> <meta name="author" content="CodersMag"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" type="image/ico" href="https://codersmag.com/demos/ci/assets/images/favicon.ico"> <title>Send Email with Multiple Attachments using PHP with Phpmailer | Coders Mag</title> <!-- Bootstrap core CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" /> <!-- Custom fonts for this template --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.7.2/css/all.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.css" /> <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css"> <!-- Custom styles for this template --> <link href="assets/css/style.css" rel="stylesheet"> </head> <body> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top header-bg-dark" style="background: ##FFFFFF!;"> <div class="container"> <a class="navbar-brand font-weight-bold" href="https://codersmag.com/"><h1>Coders Mag</h1></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="https://codersmag.com/">Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="https://codersmag.com/php-script-demos/">LIVE DEMO</a> </li> </ul> </div> </div> </nav> |
Step 5: Create a view file named footer.php
This view contains the footer section of the webpage.
- jQuery – needed by Bootstrap JavaScript.
- Bootstrap JavaScript – to make cool UI
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<!-- Footer --> <footer class="footer bg-light footer-bg-dark"> <div class="container"> <div class="row"> <div class="col-lg-6 h-100 text-center text-lg-left my-auto"> <ul class="list-inline mb-2"> <li class="list-inline-item"> <a href="#">About</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Contact</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Terms of Use</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Privacy Policy</a> </li> </ul> <p class="small mb-4 mb-lg-0" style="color: #E6ECF0;">Copyright © 2017 - <?php print date('Y', time());?> <a style="color: #E6ECF0;" href="https://codersmag.com/">CODERSMAG.COM</a> All rights reserved.</p> </div> <div class="col-lg-6 h-100 text-center text-lg-right my-auto"> <ul class="list-inline mb-0"> <li class="list-inline-item mr-3"> <a href="#"> <i class="fab fa-facebook fa-2x fa-fw"></i> </a> </li> <li class="list-inline-item mr-3"> <a href="#"> <i class="fab fa-twitter-square fa-2x fa-fw"></i> </a> </li> <li class="list-inline-item"> <a href="#"> <i class="fab fa-instagram fa-2x fa-fw"></i> </a> </li> </ul> </div> </div> </div> </footer> <!-- Bootstrap core JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> </body> </html> |