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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.