email sendingIn this tutorial we will tell you How to Sending attachments with email using PHP.Mean How To send an email with mixed content requires to set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries.

A boundary is started with two hyphens followed by a unique number which can not appear in the message part of the email. A PHP function md5() is used to create a 32 digit hexadecimal number to create unique number. A final boundary denoting the email’s final section must also end with two hyphens.

Attached files should be encoded with the base64_encode() function for safer transmission and are best split into chunks with the chunk_split() function. This adds rn inside the file at regular intervals, normally every 76 characters.

Following is the example which will send a file /tmp/test.txt as an attachment. you can code your program to receive an uploaded file and send it.

<html>
<head>
<title>Sending attachment using PHP</title>
</head>
<body>
<?php
  $to = "[email protected]";
  $subject = "This is subject";
  $message = "This is test message.";
  # Open a file
  $file = fopen( "/tmp/test.txt", "r" );
  if( $file == false )
  {
     echo "Error in opening file";
     exit();
  }
  # Read the file into a variable
  $size = filesize("/tmp/test.txt");
  $content = fread( $file, $size);

  # encode the data for safe transit
  # and insert rn after every 76 chars.
  $encoded_content = chunk_split( base64_encode($content));

  # Get a random 32 bit number using time() as seed.
  $num = md5( time() );

  # Define the main headers.
  $header = "From:[email protected]";
  $header .= "MIME-Version: 1.0rn";
  $header .= "Content-Type: multipart/mixed; ";
  $header .= "boundary=$numrn";
  $header .= "--$numrn";

  # Define the message section
  $header .= "Content-Type: text/plainrn";
  $header .= "Content-Transfer-Encoding:8bitrnn";
  $header .= "$messagern";
  $header .= "--$numrn";

  # Define the attachment section
  $header .= "Content-Type:  multipart/mixed; ";
  $header .= "name="test.txt"rn";
  $header .= "Content-Transfer-Encoding:base64rn";
  $header .= "Content-Disposition:attachment; ";
  $header .= "filename="test.txt"rnn";
  $header .= "$encoded_contentrn";
  $header .= "--$num--";

  # Send email now
  $retval = mail ( $to, $subject, "", $header );
  if( $retval == true )
   {
      echo "Message sent successfully...";
   }
   else
   {
      echo "Message could not be sent...";
   }
?>
</body>
</html>

Sending plain text email using PHP

Sending HTML email using PHP

Sending attachments with email using PHP

One thought on “Sending attachments with email using PHP

  1. A simpler solution that will work better is to use a library like the Ultimate Email Toolkit, PHP Mailer, or SwiftMailer.

Leave a Reply

Your email address will not be published. Required fields are marked *