Narendra123

send email with attachment file

Jul 18th, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. <form name="form1" enctype="multipart/form-data" method="post" action="">
  2. <label>Your Name
  3. <input type="text" name="name" />
  4. </label>
  5. <label>Your Email
  6. <input type="email" name="email" />
  7. </label>
  8. <label>Attachment
  9. <input type="file" name="my_file" />
  10. </label>
  11. <label>
  12. <input type="submit" name="button" value="Submit" />
  13. </label>
  14. </form>
  15. <?php
  16. if($_POST && isset($_FILES['my_file']))
  17. {
  18.  
  19. $from_email = 'sender_mail@example.com'; //sender email
  20. $recipient_email = 'recipient_mail@example.com'; //recipient email
  21. $subject = 'Test mail'; //subject of email
  22. $message = 'This is body of the message'; //message body
  23.  
  24. //get file details we need
  25. $file_tmp_name = $_FILES['my_file']['tmp_name'];
  26. $file_name = $_FILES['my_file']['name'];
  27. $file_size = $_FILES['my_file']['size'];
  28. $file_type = $_FILES['my_file']['type'];
  29. $file_error = $_FILES['my_file']['error'];
  30.  
  31. $user_email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
  32.  
  33. if($file_error>0)
  34. {
  35. die('upload error');
  36. }
  37. //read from the uploaded file & base64_encode content for the mail
  38. $handle = fopen($file_tmp_name, "r");
  39. $content = fread($handle, $file_size);
  40. fclose($handle);
  41. $encoded_content = chunk_split(base64_encode($content));
  42.  
  43.  
  44. $boundary = md5("sanwebe");
  45. //header
  46. $headers = "MIME-Version: 1.0\r\n";
  47. $headers .= "From:".$from_email."\r\n";
  48. $headers .= "Reply-To: ".$user_email."" . "\r\n";
  49. $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
  50.  
  51. //plain text
  52. $body = "--$boundary\r\n";
  53. $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
  54. $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
  55. $body .= chunk_split(base64_encode($message));
  56.  
  57. //attachment
  58. $body .= "--$boundary\r\n";
  59. $body .="Content-Type: $file_type; name=\"$file_name\"\r\n";
  60. $body .="Content-Disposition: attachment; filename=\"$file_name\"\r\n";
  61. $body .="Content-Transfer-Encoding: base64\r\n";
  62. $body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
  63. $body .= $encoded_content;
  64.  
  65. $sentMail = @mail($recipient_email, $subject, $body, $headers);
  66. if($sentMail) //output success or failure messages
  67. {
  68. die('Thank you for your email');
  69. }else{
  70. die('Could not send mail! Please check your PHP mail configuration.');
  71. }
  72.  
  73. }
Add Comment
Please, Sign In to add comment