In previous example we’ve learned how to send PHP mail with an attachment, and I have also created separate Ajax tutorial for the same. But some of you also want to send multiple attachments, so today I am going to refine the PHP code to show you how we can send multiple attachments with PHP mail.
First we need to create HTML multipart/form-data form with file input fields.
You can turn those file fields into associative arrays using square brackets as shown below, or add attribute multiple=”multiple” in file input tag. this way no matter how many fields we add, we can simply iterate each field and access their variables later. Have a look at HTML form code below :
Once you are done with HTML part, you can examine the code below and copy it in a file and name it as send_attachments.php, which is the PHP file pointed in action parameter in HTML form above.
The PHP code simply iterates though uploaded files, creates base64 encoded strings and combines them in single mail body encapsulated in boundaries.
That’s it, the PHP script now should send multiple attachments. If you encounter any error during file upload, you may need to set the value of upload_max_filesize and post_max_size in your php.ini, because it determines the size of file you can upload.
Check-out Ajax Contact Form with an Attachment for Ajax tutorial.