Monday, October 2, 2017

Send file to email address using php mail function

In this tutorials, we will discuss about the PHP mail Function, which helps you to send an email to desire destination. Apart from the sending email, also we will cover topic how we can send an Attachment/File using PHP mail function.

To send an email, we have to mention some additional header information to send an email, lets see the below source code to get more information.

Example: Send file to email address/ Send Mail with an Attachment

  $to = "";  
  $subject = "This is subject";  
  $message = "This is a text message.";  
  # Open a file  
  $file = fopen("/doc/file.txt", "r" );//change your file location  
  if( $file == false )  
     echo "Error in opening file";  
  # Read the file into a variable  
  $size = filesize("/doc/file.txt");  
  $content = fread( $file, $size);  
  # encode the data for safe transit  
  # and insert \r\n 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 = "\r\n";  
  $header .= "MIME-Version: 1.0\r\n";  
  $header .= "Content-Type: multipart/mixed; ";  
  $header .= "boundary=$num\r\n";  
  $header .= "--$num\r\n";  
  # Define the message section  
  $header .= "Content-Type: text/plain\r\n";  
  $header .= "Content-Transfer-Encoding:8bit\r\n\n";  
  $header .= "$message\r\n";  
  $header .= "--$num\r\n";  
  # Define the attachment section  
  $header .= "Content-Type:  multipart/mixed; ";  
  $header .= "name=\"test.txt\"\r\n";  
  $header .= "Content-Transfer-Encoding:base64\r\n";  
  $header .= "Content-Disposition:attachment; ";  
  $header .= "filename=\"test.txt\"\r\n\n";  
  $header .= "$encoded_content\r\n";  
  $header .= "--$num--";  
  # Send email now  
  $result = mail ( $to, $subject, "", $header );  
  if( $result == true ){  
      echo "Message sent successfully...";  
      echo "Sorry, unable to send mail...";  

No comments:

Post a Comment