Posted By

IanLewis on 05/21/07


Tagged

mail e-mail encoding multi-part


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

vali29
hudge
oli964
skywalker


Send multi-part encoded mail with attachments.


 / Published in: PHP
 

Sends mail to the e-mail address specified. Supports attaching files, multi-part message, and e-mail encodings. Works well with Asian cell phones.

  1. /**
  2.  * Sends mail to the e-mail address given.
  3.  * Supports attaching files and multiple encodings.
  4.  * @param string The email address of the recipient
  5.  * @param string The name to include in the from header
  6.  * @param string The e-mail address to include in the from header
  7.  * @param string the e-mail subject
  8.  * @param string the e-mail body.
  9.  * @param boolean true if the body is html or false if plain text.
  10.  * @param string a path to a file on the server to attach to the e-mail. Null or an empty string indicates that there is no attachment.
  11.  * @param string the encoding with which to encode the subject, from, and body.
  12.  */
  13. function SendMail($emailaddress,
  14. $from, $fromaddress,
  15. $emailsubject="",
  16. $body="", $html = true,
  17. $attachment="",
  18. $encoding="utf-8") {//{{{
  19.  
  20. # Is the OS Windows or Mac or Linux
  21. if (strtoupper(substr(PHP_OS,0,3)=='WIN')) {
  22. $eol="
  23. ";
  24. } elseif (strtoupper(substr(PHP_OS,0,3)=='MAC')) {
  25. $eol="\r";
  26. } else {
  27. $eol="\n";
  28. }
  29.  
  30. //set subject encoding
  31. if (!empty($emailsubject)) {
  32. $emailsubject = encode_mail_string($emailsubject, $encoding);
  33. }
  34. $from = encode_mail_string($from, $encoding);
  35. if ($encoding != "utf-8" && !empty($body)) {
  36. $body = mb_convert_encoding($body, $encoding, "utf-8");
  37. }
  38.  
  39. $msg = "";
  40.  
  41. # Common Headers
  42. $headers .= "From: ".$from." <".$fromaddress.">".$eol;
  43. $headers .= "Reply-To: ".$from." <".$fromaddress.">".$eol;
  44. $headers .= "Return-Path: ".$from." <".$fromaddress.">".$eol; // these two to set reply address
  45. $headers .= "Message-ID: <".time()." TheSystem@".$_SERVER['SERVER_NAME'].">".$eol;
  46. $headers .= "X-Mailer: PHP v".phpversion().$eol; // These two to help avoid spam-filters
  47. $headers .= 'MIME-Version: 1.0'.$eol;
  48.  
  49. if (!empty($attachment)) {
  50. //send multipart message
  51. # Boundry for marking the split & Multitype Headers
  52. $mime_boundary=md5(time());
  53. $headers .= "Content-Type: multipart/related; boundary=\"".$mime_boundary."\"".$eol;
  54.  
  55. # File for Attachment
  56.  
  57. $f_name = $attachment;
  58. $handle=fopen($f_name, 'rb');
  59. $f_contents=fread($handle, filesize($f_name));
  60. $f_contents=chunk_split(base64_encode($f_contents));//Encode The Data For Transition using base64_encode();
  61. $f_type=filetype($f_name);
  62. fclose($handle);
  63.  
  64. # Attachment
  65. $msg .= "--".$mime_boundary.$eol;
  66. $msg .= "Content-Type: application/jpeg; name=\"".$file."\"".$eol;
  67. $msg .= "Content-Transfer-Encoding: base64".$eol;
  68. $msg .= "Content-Disposition: attachment; filename=\"".basename($attachment)."\"".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
  69. $msg .= $f_contents.$eol.$eol;
  70. # Setup for text OR html
  71. $msg .= "Content-Type: multipart/alternative".$eol;
  72.  
  73.  
  74. $contentType = "text/plain";
  75. if ($html) {
  76. $contentType = "text/html";
  77. }
  78.  
  79. # Body
  80. $msg .= "--".$mime_boundary.$eol;
  81. $msg .= "Content-Type: ".$contentType."; charset=\"".$encoding."\"".$eol;
  82. $msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
  83. $msg .= $body.$eol.$eol;
  84.  
  85. # Finished
  86. $msg .= "--".$mime_boundary."--".$eol.$eol; // finish with two eol's for better security. see Injection.
  87. } else {
  88. $headers .= "Content-Type: text/plain; charset=\"".$encoding."\"".$eol;
  89. $headers .= "Content-Transfer-Encoding: 8bit".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
  90. $msg .= $body.$eol.$eol;
  91. }
  92.  
  93. // SEND THE EMAIL
  94. //LogMessage("Sending mail to: ".$emailaddress." => ".$emailsubject);
  95.  
  96. //ini_set(sendmail_from, '[email protected]'); // the INI lines are to force the From Address to be used !
  97. ini_set(sendmail_from, $fromaddress); //needed to hopefully get by spam filters.
  98. $success = mail($emailaddress, $emailsubject, $msg, $headers);
  99. ini_restore(sendmail_from);
  100.  
  101. return $success;
  102. }//}}}

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: jorix on January 6, 2010

Line 32 throws an error as the function encodemailstring() is not defined

Posted By: isuPatches328 on April 15, 2013

Thank you so much for sharing this! I used it on my own personal website, and after days of tearing my hair out, it was great to have code that worked! I can finally let people send me error reports with an attached screen shot through a web form :) Here's my version of it:

// A function that sends a mail with or without an attachment function SendMail($emailaddress, $from, $fromaddress, $emailsubject="", $body="", $html = true, $attachment="", $attachmenttype, $encoding="utf-8") { // Comments left in for debugging purposes
/*echo("

Attachment: "); echo($attachment); echo("

");

    echo("<p>Attachment type: ");
    echo($attachmenttype);
    echo("</p>");*/

    // Setting proper EOL character, and making sure msg is blank to begin with
    $eol= "\n";                                 
    $msg = "";

    // Headers for the message
    $headers .= "From: " . $from . " " . $eol;
    $headers .= "CC: Patches " . $eol; // Not enough space on godaddy email account, so directed right to sklinefelter89@gmail
    $headers .= "Reply-To: " . $fromaddress . $eol;
    $headers .= "Message-ID: " .$eol;  // This helps to avoid spam-filters
    $headers .= "X-Mailer: PHP v" . phpversion() . $eol; // This helps to avoid spam-filters     
    $headers .= 'MIME-Version: 1.0' . $eol;

    // Comments left in for debugging purposes          
    /*echo("<p>Headers: ");
    echo($headers);
    echo("</p>");*/

    if (!empty($attachment)) 
    {
        // Comments left in for debugging purposes  
        /*echo("<p>Attachment is not empty</p>");

        echo("<p>Attachment: ");
        echo($attachment);
        echo("</p>");*/

        // Setting up to send a multipart message with boundaries
        // Getting a boudary to mark the different sections
        $mime_boundary = md5(time());

        // Comments left in for debugging purposes          
        /*echo("<p>MIME boundary: ");
        echo($mime_boundary);
        echo("</p>");*/

        // A boundary for the next section
        $headers .= "Content-Type: multipart/mixed; boundary=\"" . $mime_boundary . "\"" . $eol;

        // Comments left in for debugging purposes  
        /*echo("<p>Headers: ");
        echo($headers);
        echo("</p>");*/

        // Working with the file, opening it, reading it, encoding it, and getting the type, etc.
        $handle = fopen($attachment, 'rb');
        $f_contents = fread($handle, filesize($attachment));
        $f_contents = chunk_split(base64_encode($f_contents)); // Encoding the date for the transition by using base64_encode()
        $f_type = filetype($attachment);
        fclose($handle);            

        // The information for the attachment
        $msg .= "--" . $mime_boundary . $eol;
        $msg .= "Content-Type: " . $attachmenttype . "; name=\"" . $attachment . "\"" . $eol;
        $msg .= "Content-Transfer-Encoding: base64" . $eol;
        $msg .= "Content-Disposition: attachment; filename=\"".basename($attachment)."\"" . $eol . $eol; // !! This line needs TWO end of lines !! IMPORTANT !!
        $msg .= $f_contents . $eol . $eol;

        // Setup for text OR html, choose to go with multipart/mixed
        $msg .= "Content-Type: multipart/mixed".$eol;

        // Comments left in for debugging purposes          
        /*echo("<p>attachment: ");
        echo($attachment);
        echo("</p>");

        if(file_exists($attachment))
        {
            echo("<p>The file exists</p>");
        }
        else
        {
            echo("<p>The file does not exist</p>");
        }

        echo("<p>Base name attachent: ");
        echo(basename($attachment));
        echo("</p>");

        echo("<p>Message: ");
        echo($msg);
        echo("</p>");*/

        // Checks if content will be html or not and sets $contentType appropriately
        $contentType = "text/plain";
        if ($html) 
        {
            $contentType = "text/html";
        }

        // A boundary for the next section
        $msg .= "--" . $mime_boundary . $eol;

        // Comments left in for debugging purposes
        /*echo("<p>Content Type: ");
        echo($contentType);
        echo("</p>");

        echo("<p>Econding: ");
        echo($encoding);
        echo("</p>");*/

        $msg .= "Content-Type: " . $contentType . "; charset=\"" . $encoding . "\"" . $eol;
        $msg .= "Content-Transfer-Encoding: 8bit" . $eol . $eol; // !! This line needs TWO end of lines !! IMPORTANT !!
        $msg .= $body . $eol . $eol;

        // The end boundary
        $msg .= "--" . $mime_boundary . "--" . $eol . $eol;  // finish with two eol's for better security. see Injection.
    } 
    else 
    {
        // For when there is not an attachment, we get here
        $headers .= "Content-Type: text/html; charset=\"".$encoding."\"".$eol;
        $headers .= "Content-Transfer-Encoding: 8bit".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
        $msg .= $body . $eol . $eol;
    }

    // The INI lines are to force the From Address to be used
    ini_set(sendmail_from, $fromaddress);
    // Sends the mail and returns $success which is a boolean value
    $success = mail($emailaddress, $emailsubject, $msg, $headers);
    ini_restore(sendmail_from);

    // Comments left in for debugging purposes
    /*if($success)
    {
        echo("<p>Sent mail successfully</p>");
    }
    else
    {
        echo("<p>Did not send mail successfully</p>");
    }*/

    return $success;
}

You need to login to post a comment.