Browse by Month RSS Feed
  • February 2010
  • January 2010
  • December 2009
  • November 2009
  • October 2009
  • September 2009

  • Filed under: Code, PHP @ 9:34 pm

    I got this sucker working for Form Tools last month after working my butt off making sense of the many idiosyncracies of the many servers out there. Well, turns out I missed a problem. After half a dozen people complained I bumped this up on my priorities and investigated it.

    If you need to ever send HTML+text emails in PHP, I'd thoroughly recommend the following article: http://www.zend.com/zend/trick/html-email.php

    But be careful not to deviate from the example code without fully understanding it! Every last aspect of the code is there for a purpose, including the occasional double endlines. Unfortunately, the writer doesn't delve into the details in any great depth so one is apt to assume they're not important. One thing that's not covered is determining an endline based on OS type. Here's my tweaked version:

    PHP:
    1. // determine the end of line character (based on OS)
    2. $eol = "\n";
    3. if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN'))
    4. $eol = "\r\n";
    5. else if (strtoupper(substr(PHP_OS, 0, 3) == 'MAC'))
    6. $eol = "\r";
    7.  
    8. // add From: header
    9. $headers = "From: webserver@localhost$eol";
    10.  
    11. //specify MIME version 1.0
    12. $headers .= "MIME-Version: 1.0$eol";
    13.  
    14. // unique boundary
    15. $boundary = uniqid("HTMLDEMO");
    16.  
    17. // tell e-mail client this e-mail contains alternate versions
    18. $headers .= "Content-Type: multipart/alternative" .
    19. "; boundary = $boundary$eol$eol";
    20.  
    21. // message to people with clients who don't understand MIME
    22. $headers .= "This is a MIME encoded message.$eol";
    23.  
    24. // plain text version of message
    25. $headers .= "--$boundary$eol" .
    26. "Content-Type: text/plain; charset=ISO-8859-1$eol" .
    27. "Content-Transfer-Encoding: base64$eol$eol";
    28. $headers .= chunk_split(base64_encode("This is the plain text version!"));
    29.  
    30. // HTML version of message
    31. $headers .= "--$boundary\r\n" .
    32. "Content-Type: text/html; charset=ISO-8859-1$eol" .
    33. "Content-Transfer-Encoding: base64$eol$eol";
    34. $headers .= chunk_split(base64_encode("This the <strong>HTML</strong> version!"));
    35.  
    36. // send message
    37. mail("root@localhost", "An HTML Message", "", $headers);

    I can vouch for the code working on Windows and Unix servers. Good luck...!


    No Comments »

    No comments yet.

    RSS feed for comments on this post. TrackBack URI

    Leave a comment