PHP

How to send attachment in an email using PHP

This tutorial will explain you How to send attachment in an email using PHP by uploading the file using HTML form with a simple example. You will also learn how you can send multiple attachment by some little modification in the code of single file attachment.

First of all we need an HTML Form through which we will upload the file. Below is the HTML Form code:

Note the “enctype” attribute in form tag. This is an attribute that specifies the encoding type used while sending data to server. Whenever we use any file input tag in our we need to specify this attribute in form tag with value “multipart/form-data”. This encoding type “multipart/form-data” tells that no character will be encoded while sending. It helps in preserving the data of uploaded file. One more thing to note that the enctype attribute is used only with post method.

Now lets take a look at the php file sendemail.php that does the actual task of sending uploaded file to email address.

Files in email are being sent in base64 encoding format. In above code we are converting the content of uploaded file into base64 format and then splitting the content into small chunks using chink_split function in case the file size is bigger.

Similarly if we want to send multiple files in attachment, we just need made some modification in the code of both files to make it work in case of multiple file attachment and sending it to email address. Below we’ll take a look of revised version of both files to accomplish the task to sending multiple files in email attachment.

Note the two addition I made in above code. First addition is adding brackets in name attributes of input file tag and the second addition is multiple attribute. This attribute “multiple” allows us to upload multiple files and those files are assigned to an array of files specified by name “file[]”.

In above code there is just one addition that is the for loop around the if condition that collects each individual files from the “file[]” array passed from the HTML Form and pass it for further processing as we done in earlier version of sendemail.php

About the author

Sujeet Kr Singh