PHP code for sending email with attachments Very simple codes to send email in php server. codes are tested your just need to copy and paste.

HTML code to submit message



file:contact.php

<!DOCTYPE html>

<html>

<head>

<title>Page Title</title>

</head>

<body>

<b>Send this message to mail</b><br/>

 <form method="post"  action="contact_process.php"  enctype="multipart/form-data">

     <b>Subject: </b><input name="subject" type="text"><br/>

    <b>Message: </b><input name="message" type="text"><br/>

    <b>File: </b><input name="attachment" type="file"><br/>

<input name="submit" type="submit" value="Send"><br/>

</form>

</body>

</html>

PHP code to process and send details with attachment to email address



<?php 

//get data from form  

$form_subject= $_POST['subject'];

$form_message= $_POST['message'];

//fixed recipient details

$mail_to = "sendtothisemail@abc.com";

$mail_from = "fromxyg@xyz.com";

$mail_subject =$form_subject; 

   

//---------------tested ok for uploading file from browser----- 

//START- Encoding attachment for mail

// attachment

$file = $_FILES["attachment"]["tmp_name"];

$filename = $_FILES["attachment"]["name"];

$attachment = chunk_split(base64_encode(file_get_contents($file)));

# encode the data for safe transit  

# and insert after every 76 chars.  

//$attachment = chunk_split( base64_encode($attachment)); 

  # Get a random 32 bit number using time() as seed.  

  $num = md5( time() );  



  # Define the main headers.  

  $header = "From:".$mail_from." ";  

  $header .= "MIME-Version: 1.0 ";  

  $header .= "Content-Type: multipart/mixed; ";  

  $header .= "boundary=".$num." ";  

 

 

   

  # Define the message section

  $message .= "--".$num." ";  

  $message .= "Content-Type: text/plain ";  

  $message .= "Content-Transfer-Encoding:8bit ";  

  $message .= $form_message." ";  

  $message .= "--".$num." ";  

  

  # Define the attachment section  

  $message .= "Content-Type:  multipart/mixed; ";  

  $message .= "name="test.txt" ";  

  $message .= "Content-Transfer-Encoding:base64 ";  

  $message .= "Content-Disposition:attachment; ";  

  $message .= "filename="".$filename."" ";  

  $message .= $attachment." ";  

  $message .= "--".$num."--";  

   //START- Encoding attachment for mail

  //---------------tested ok for uploading file from browser-----*/