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 to a network, sending a newsletter, sending greeting mail, 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, subject of the message and message body. Along with this 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 mail() 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.

Name Description Required/Optional Type
to This contains the receiver or receivers of the particular email Required String
subject This conatains 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 a LF ( ). Lines should not exceed 70 characters (We will use wordwrap() function to achieve this.) Required String
headers This conatins additional headers, like From, Cc, Mime Version, Bcc. Optional String
parameters Specifies an additional parameter to the send mail program Optional String

When we are sending a 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.

Create an HTML form:

<form enctype="multipart/form-data" method="POST" action="">
    <label>Your Name <input type="text" name="sender_name" /> </label
    <label>Your Email <input type="email" name="sender_email" /> </label
    <label>Subject <input type="text" name="subject" /> </label
    <label>Message <textarea name="message"></textarea> </label
    <label>Attachment <input type="file" name="attachment" /></label>
    <label><input type="submit" name="button" value="Submit" /></label>

PHP Script for handling the form data:

if($_POST['button'] && isset($_FILES['attachment']))
    $from_email         = '[email protected]'; //from mail, sender email addrress
    $recipient_email    = '[email protected]'; //recipient email addrress
    //Load POST data from HTML form
    $sender_name    = $_POST["sender_name"] //sender name
    $reply_to_email = $_POST["sender_email"] //sender email, it will be used in "reply-to" header
    $subject        = $_POST["subject"] //subject for the email
    $message        = $_POST["message"] //body of the email
    /*Always remember to validate the form fields like this
        die('Name is too short or empty!');
    //Get uploaded file data using $_FILES array
    $tmp_name    = $_FILES['my_file']['tmp_name']; // get the temporary file name of the file on the server
    $name        = $_FILES['my_file']['name'];  // get the name of the file
    $size        = $_FILES['my_file']['size'];  // get size of the file for size validation
    $type        = $_FILES['my_file']['type'];  // get type of the file
    $error       = $_FILES['my_file']['error']; // get the error (if any)
    //validate form field for attaching the file
    if($file_error > 0)
        die('Upload error or No files uploaded');
    //read from the uploaded file & base64_encode content
    $handle = fopen($tmp_name, "r");  // set the file handle only for reading the file
    $content = fread($handle, $size); // reading the file
    fclose($handle);                  // close upon completion
    $encoded_content = chunk_split(base64_encode($content));
    $boundary = md5("random"); // define boundary with a md5 hashed value
    $headers = "MIME-Version: 1.0 "; // Defining the MIME version
    $headers .= "From:".$from_email." "; // Sender Email
    $headers .= "Reply-To: ".$reply_to_email." "; // Email addrress to reach back
    $headers .= "Content-Type: multipart/mixed; "; // Defining Content-Type
    $headers .= "boundary = $boundary "; //Defining the Boundary
    //plain text 
    $body = "--$boundary ";
    $body .= "Content-Type: text/plain; charset=ISO-8859-1 ";
    $body .= "Content-Transfer-Encoding: base64 "
    $body .= chunk_split(base64_encode($message)); 
    $body .= "--$boundary ";
    $body .="Content-Type: $file_type; name=".$file_name." ";
    $body .="Content-Disposition: attachment; filename=".$file_name." ";
    $body .="Content-Transfer-Encoding: base64 ";
    $body .="X-Attachment-Id: ".rand(1000, 99999)." "
    $body .= $encoded_content; // Attaching the encoded file with email
    $sentMailResult = mail($recipient_email, $subject, $body, $headers);
       echo "File Sent Successfully.";
       unlink($name); // delete the file after attachment sent.
       die("Sorry but the email could not be sent.
                    Please go back and try again!");

This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment



load comments

Subscribe to Our Newsletter