fbpx
Friday, December 8, 2023
Hire us on Freelancer.com for web development service
HomeLogin FormSend mail with attachment in php

Send mail with attachment in php

In the world of web development, communication is key. Often, we need to send emails programmatically with attachments, which is a common task in web applications. In this guide, we will explore how to send mail with file attachment in PHP. We will break down the process into easy-to-follow steps, answering key questions along the way.

Setting Up Your Environment

Before we dive into the specifics of sending emails with attachments in PHP, ensure that you have the following prerequisites in place:

A web server (e.g., Apache or Nginx) with PHP installed.
A valid email account to send emails from.
Basic knowledge of PHP programming.

Step 2: Writing the PHP Code
To send an email with an attachment in PHP, follow these steps:

<?php

    session_start();
    
   $from_email     = $_POST['email'];; //from mail, sender email address
   $recipient_email = 'yourmail@gmail.com'; //recipient email address
   
   //Load POST data from HTML form
   $sender_name = $_POST["name"]; //sender name
   $reply_to_email = $_POST["email"]; //sender email, it will be used in "reply-to" header
   $subject  = $_POST["subject"]; //subject for the email
   $message  = $_POST["msg"]; //body of the email
    $message = $_POST["phone"];
    
   //Get uploaded file data using $_FILES array
   $tmp_name = $_FILES['attachment']['tmp_name']; // get the temporary file name of the file on the server
   $name  = $_FILES['attachment']['name']; // get the name of the file
   $size  = $_FILES['attachment']['size']; // get size of the file for size validation
   $type  = $_FILES['attachment']['type']; // get type of the file
   $error    = $_FILES['attachment']['error']; // get the error (if any)

   //validate form field for attaching the file
   if($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

   //header
   $headers = "MIME-Version: 1.0\r\n"; // Defining the MIME version
   $headers .= "From:".$from_email."\r\n"; // Sender Email
   $headers .= "Reply-To: ".$reply_to_email."\r\n"; // Email address to reach back
   $headers .= "Content-Type: multipart/mixed;"; // Defining Content-Type
   $headers .= "boundary = $boundary\r\n"; //Defining the Boundary
      
   //plain 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));
      
   //attachment
   $body .= "--$boundary\r\n";
   $body .="Content-Type: $type; name=".$name."\r\n";
   $body .="Content-Disposition: attachment; filename=".$name."\r\n";
   $body .="Content-Transfer-Encoding: base64\r\n";
   $body .="X-Attachment-Id: ".rand(1000, 99999)."\r\n\r\n";
   $body .= $encoded_content; // Attaching the encoded file with email
   
   $sentMailResult = mail($recipient_email, $subject, $body, $headers);

   if($sentMailResult )
   {
        $_SESSION['Success'] = "Message Sent Successfully";
        header('location: contact.php');
   }
   else
   {
   die("Sorry but the email could not be sent.
               Please go back and try again!");
   }

?>

Conclusion

Sending emails with attachments in PHP is an essential skill for web developers. To enhance your knowledge, you can refer to this helpful article on how to activate and deactivate status in PHP. By mastering send mail with file attachment in php functionalities, you’ll be better equipped to build dynamic and interactive web applications.

Source Code: 

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Hire Us

Categories