PHP | Send Attachment With Email
Sending an email is a very common activity in a web browser. For example, sending an email when a new user joins a network, sending a newsletter, sending greeting mail, or sending an invoice. We can use the built-in mail() function to send an email programmatically. This function needs three required arguments that hold the information about the recipient, the subject of the message and the message body. Along with these three required arguments, there are two more arguments which are optional. One of them is the header and the other one is parameters.
We have already discussed sending text-based emails in PHP in our previous article. In this article, we will see how we can send an email with attachments using the Mime-Versionmail() function.
When the mail() function is called PHP will attempt to send the mail immediately to the recipient then it will return true upon successful delivery of the mail and false if an error occurs.
bool mail( $to, $subject, $message, $headers, $parameters );
Here is the description of each parameter.
|to||This contains the receiver or receivers of the particular email||Required||String|
|subject||This contains the subject of the email. This parameter cannot contain any newline characters||Required||String|
|message||This contains the message to be sent. Each line should be separated with an LF (\n). Lines should not exceed 70 characters (We will use wordwrap() function to achieve this.)||Required||String|
|headers||This contains additional headers, like From, Cc, Mime Version, and Bcc.||Optional||String|
|parameters||Specifies an additional parameter to the send mail program||Optional||String|
When we are sending mail through PHP, all content in the message will be treated as simple text only. If we put any HTML tag inside the message body, it will not be formatted as HTML syntax. HTML tag will be displayed as simple text.
To format any HTML tag according to HTML syntax, we can specify the MIME (Multipurpose Internet Mail Extension) version, content type and character set of the message body.
To send an attachment along with the email, we need to set the Content-type as mixed/multipart and we have to define the text and attachment sections within a Boundary.
Follow the steps given below:
Create an HTML form: Below is the HTML source code for the HTML form. In the HTML <form> tag, we are using “enctype=’multipart/form-data” which is an encoding type that allows files to be sent through a POST method. Without this encoding, the files cannot be sent through the POST method. We must use this enctype if you want to allow users to upload a file through a form.
PHP Script for handling the form data:
Complete Code: The final code for sending attachments with Emails is as follows: