Sending emails with attachment and HTML with PHP


/ Published in: PHP
Save to your folder(s)

Function to send HTML emails with an attachment in PHP. Notes and info at the above url!


Copy this code and paste it in your HTML
  1. function mail_file( $to, $subject, $messagehtml, $from, $fileatt, $replyto="" ) {
  2.  
  3. $ext = strrchr( $fileatt , '.');
  4. $fileatttype = "";
  5. if ($ext == ".doc") $fileatttype = "application/msword";
  6. if ($ext == ".jpg") $fileatttype = "image/jpeg";
  7. if ($ext == ".gif") $fileatttype = "image/gif";
  8. if ($ext == ".pdf") $fileatttype = "application/x-pdf";
  9. if ($fileatttype=="") $fileatttype = "application/octet-stream";
  10.  
  11. $file = fopen($fileatt, "rb");
  12. $data = fread($file, filesize( $fileatt ) );
  13. fclose($file);
  14.  
  15. $content = chunk_split(base64_encode($data));
  16. $uid = md5(uniqid(time()));
  17.  
  18. $headers = "From: $from
  19. ";
  20. if ($replyto) $headers .= "Reply-To: ".$replyto."
  21. ";
  22. $headers .= "MIME-Version: 1.0
  23. ";
  24. $headers .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"
  25.  
  26. ";
  27. $headers .= "This is a multi-part message in MIME format.
  28. ";
  29. $headers .= "--".$uid."
  30. ";
  31. $headers .= "Content-type:text/html; charset=iso-8859-1
  32. ";
  33. $headers .= "Content-Transfer-Encoding: 7bit
  34.  
  35. ";
  36. $headers .= $messagehtml."
  37.  
  38. ";
  39. $headers .= "--".$uid."
  40. ";
  41. $headers .= "Content-Type: ".$fileatttype."; name=\"".basename($fileatt)."\"
  42. ";
  43. $headers .= "Content-Transfer-Encoding: base64
  44. ";
  45. $headers .= "Content-Disposition: attachment; filename=\"".basename($fileatt)."\"
  46.  
  47. ";
  48. $headers .= $content."
  49.  
  50. ";
  51. $headers .= "--".$uid."--";
  52.  
  53. return mail( $to, $subject, strip_tags($messagehtml), str_replace("
  54. ","\n",$headers) ) ;
  55.  
  56. }

URL: http://www.barattalo.it/2010/01/10/sending-emails-with-attachment-and-html-with-php/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.