PHP: Send Plaintext + HTML Email


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



Copy this code and paste it in your HTML
  1. <?php
  2. //define the receiver of the email
  3. //define the subject of the email
  4. $subject = 'Test HTML email';
  5.  
  6. // Generate a random boundary string
  7. $mime_boundary = '_x'.sha1(time()).'x';
  8.  
  9. // Using the heredoc syntax to declare the headers
  10. $headers = <<<HEADERS
  11. From: Test <[email protected]>
  12. MIME-Version: 1.0
  13. Content-Type: multipart/alternative;
  14.  boundary="PHP-alt$mime_boundary"
  15. HEADERS;
  16.  
  17. // Use our boundary string to create plain text and HTML versions
  18. $message = <<<MESSAGE
  19. --PHP-alt$mime_boundary
  20. Content-Type: text/plain; charset="iso-8859-1"
  21. Content-Transfer-Encoding: 7bit
  22.  
  23. This Is a Plain Text Email
  24.  
  25. This message has no HTML. http://w3schools.com
  26.  
  27. --PHP-alt$mime_boundary
  28. Content-type: text/html; charset=iso-8859-1
  29. Content-Transfer-Encoding: 7bit
  30.  
  31. <html>
  32. <body>
  33. <h1>This Is an HTML Email</h1>
  34. <p>
  35. This message is composed in <a href="http://w3schools.com">HTML</a>.
  36. </p>
  37. </body>
  38. </html>
  39. --PHP-alt$mime_boundary--
  40. MESSAGE;
  41.  
  42. // Send the message
  43. if(!mail($to, $subject, $message, $headers))
  44. {
  45. // If the mail function fails, return an error message
  46. echo "Something went wrong!";
  47. }
  48. else
  49. {
  50. // Return a success message if nothing went wrong
  51. echo "Message sent successfully. Check your email!";
  52. }
  53. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.