Skip to content
  • Github
  • Facebook
  • twitter
  • About Us
  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Site Map

XpertPhp

Expertphp Is The Best Tutorial For Beginners

  • Home
  • Javascript
    • Jquery
    • React JS
    • Angularjs
    • Angular
    • Nodejs
  • Codeigniter
  • Laravel
  • Contact Us
  • About Us
  • Live Demos
How To Send Mail With Multiple Attachment In PHP

How to Send mail with Multiple Attachment in PHP

Posted on July 28, 2018December 17, 2022 By XpertPhp

In this article, we will explain to you how to send mail with multiple attachment in PHP. here we are using the simple PHP mail function.

sometimes we use to send email functionality such as send invoices to send newsletter and contact form etc.

Read Also:
How to Send Email with Attachment in PHP

In this example, we will create the form using the bootstrap. we have to pass the form attribute “multipart/form-data“ for the file upload. so we will take some fields to create the form and pass the form attribute “multipart/form-data“.

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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
<?php
$recipient_email    = "admin@gmail.com"; //recepient
$from_email         = "info@xpertphp.com"; //from email using site domain.
if(isset($_POST['btnSend'])){
    
    //php validation, exit outputting json string
    if(empty($_POST["name"])){
        print 'Name is too short or empty!';
        exit;
    }
    if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)){ //email validation
        print 'Please enter a valid email!';
        exit;
    }
    if(empty($_POST["subject"])){ //check emtpy subject
        print 'Subject is required';
        exit;
    }
    if(empty($_POST["message"])){ //check emtpy message
        print 'Too short message! Please enter something.';
        exit;
    }
    $sender_name    = filter_var($_POST["name"], FILTER_SANITIZE_STRING); //capture sender name
    $sender_email   = filter_var($_POST["email"], FILTER_SANITIZE_STRING); //capture sender email
    $subject        = filter_var($_POST["subject"], FILTER_SANITIZE_STRING);
    $message        = filter_var($_POST["message"], FILTER_SANITIZE_STRING); //capture message
    $attachments = $_FILES['my_files'];
    
    $file_count = count($attachments['name']); //count total files attached
    $boundary = md5("xpertphp.com");
    
    //construct a message body to be sent to recipient
    $message_body =  "Message from $sender_name\n";
    $message_body .=  "------------------------------\n";
    $message_body .=  "$message\n";
    $message_body .=  "------------------------------\n";
    $message_body .=  "$sender_name\n";
    $message_body .=  "$sender_email\n";
    
    if($file_count > 0){ //if attachment exists
        //header
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "From:".$from_email."\r\n";
        $headers .= "Reply-To: ".$sender_email."" . "\r\n";
        $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
        
        //message text
        $body = "--$boundary\r\n";
        $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
        $body .= chunk_split(base64_encode($message_body));
        //attachments
        for ($x = 0; $x < $file_count; $x++){      
            if(!empty($attachments['name'][$x])){
                
                if($attachments['error'][$x]>0) //exit script and output error if we encounter any
                {
                    $mymsg = array(
                    1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
                    2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
                    3=>"The uploaded file was only partially uploaded",
                    4=>"No file was uploaded",
                    6=>"Missing a temporary folder" );
                    print  $mymsg[$attachments['error'][$x]];
                    exit;
                }
                
                //get file info
                $file_name = $attachments['name'][$x];
                $file_size = $attachments['size'][$x];
                $file_type = $attachments['type'][$x];
                
                //read file
                $handle = fopen($attachments['tmp_name'][$x], "r");
                $content = fread($handle, $file_size);
                fclose($handle);
                $encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)
                
                $body .= "--$boundary\r\n";
                $body .="Content-Type: $file_type; name=".$file_name."\r\n";
                $body .="Content-Disposition: attachment; filename=".$file_name."\r\n";
                $body .="Content-Transfer-Encoding: base64\r\n";
                $body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
                $body .= $encoded_content;
            }
        }
    }else{ //send plain email otherwise
       $headers = "From:".$from_email."\r\n".
        "Reply-To: ".$sender_email. "\n" .
        "X-Mailer: PHP/" . phpversion();
        $body = $message_body;
    }
        
    $sentMail = mail($recipient_email, $subject, $body, $headers);
    if($sentMail) //output success or failure messages
    {      
        print 'Thank you for your email';
        exit;
    }else{
        print 'Could not send mail! Please check your PHP mail configuration.';  
        exit;
    }
}
?>
 
<!DOCTYPE html>
<html lang="en">
<head>
  <title>How to Send mail with Multiple Attachment in PHP - XpertPhp</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
  <form method="post" enctype="multipart/form-data">
   <div class="form-group">
      <label for="name">Name:</label>
      <input type="text" class="form-control" id="name" placeholder="Enter Name" name="name">
    </div>
    <div class="form-group">
      <label for="email">Email:</label>
      <input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
    </div>
    <div class="form-group">
      <label for="subject">Subject:</label>
      <input type="text" class="form-control" id="subject" placeholder="Enter Subject" name="subject">
    </div>
    <div class="form-group">
      <label for="message">Message :</label>
      <textarea class="form-control" id="message" name="message"></textarea>
    </div>
    <div class="form-group">
      <label for="attachment">Attachment :</label>
      <input type="file" class="form-control" id="attachment" name="my_files[]" multiple/>
    </div>
    <button type="submit" name="btnSend" class="btn btn-default">Send</button>
  </form>
</div>
</body>
</html>
See also  PHP Datatables CRUD Example

Php Tags:php send email, php send email form, send mail

Post navigation

Previous Post: How to Send Email with Attachment in PHP
Next Post: show multiple checkbox checked with multiple array using php

Latest Posts

  • Laravel 12 Ajax CRUD Example
  • Laravel 12 CRUD Example Tutorial
  • How to Create Dummy Data in Laravel 11
  • Laravel 11 Yajra Datatables Example
  • Laravel 11 Ajax CRUD Example
  • Laravel 11 CRUD Example Tutorial
  • Angular 15 CRUD Application Example Tutorial
  • Laravel 10 Form Validation Example Tutorial
  • Angular 15 Custom Form Validation Example
  • Laravel 10 Send Email Example Tutorial

Tools

  • Compound Interest Calculator
  • Hex to RGB Color Converter
  • Pinterest Video Downloader
  • Birthday Calculator
  • Convert JSON to PHP Array Online
  • JavaScript Minifier
  • CSS Beautifier
  • CSS Minifier
  • JSON Beautifier
  • JSON Minifier

Categories

  • Ajax
  • Angular
  • Angularjs
  • Bootstrap
  • Codeigniter
  • Css
  • Htaccess
  • Interview
  • Javascript
  • Jquery
  • Laravel
  • MongoDB
  • MySql
  • Nodejs
  • Php
  • React JS
  • Shopify Api
  • Ubuntu

Tags

angular 10 tutorial angular 11 ci tutorial codeigniter 4 image upload Codeigniter 4 Tutorial codeigniter tutorial CodeIgniter tutorial for beginners codeigniter with mysql crud operation eloquent relationships file upload File Validation form validation Image Upload jQuery Ajax Form Handling jquery tutorial laravel 6 Laravel 6 Eloquent Laravel 6 Model laravel 6 relationship laravel 6 relationship eloquent Laravel 6 Routing laravel 7 Laravel 7 Eloquent laravel 7 routing laravel 7 tutorial Laravel 8 laravel 8 example laravel 8 tutorial laravel 9 example laravel 9 tutorial Laravel Framework laravel from scratch laravel social login learn jquery nodejs pagination payment gateway php with mysql react js example react js tutorial send mail validation wysiwyg editor wysiwyg html editor

Copyright © 2018 - 2025,

All Rights Reserved Powered by XpertPhp.com