#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    8
    Rep Power
    0

    How to format email form values as HTML?


    Hi, I have a PHP email form script that uses this to send form fields in an email as text:

    PHP Code:
    //$sFileName = $_POST["esh_formmail_save_record_file"];
    $cc $_POST["esh_formmail_cc"];
    $bcc $_POST["esh_formmail_bcc"];
    $charset $_POST["esh_formmail_charset"];


    for( 
    $i 0$i count$form_mail ); $i ++ ){
    $value trim$_POST$form_mail$i ][ "name" ] ] );


    $content .=$form_mail$i ][ "text" ] . ": \n" $value ."\n";
    $line .= remove_newline$value ) . "\t" ;
    if( 
    strtolower("Sender's email") == strtolower($form_mail$i ][ "type" ]) ) {
    //print "Type:[" . $form_mail[ $i ][ "type" ] . "] $value
    \n";
    $from = $value ;
    }

    };

    $content .= "\n\nIP:" . getEnv( "REMOTE_ADDR" ); 
    How do I get the $value form results formatted in HTML (for example bold or in multiple columns) in the email this form sends?

    Thanks much,

    MP
  2. #2
  3. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,056
    Rep Power
    9398
    How are you sending the email? Third-party library? mail()? Something else?

    The email itself needs to contain a header indicating the content is HTML. Without one it'll use the default of plain text. Once you do that then you can send a valid HTML page as an email.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    8
    Rep Power
    0
    Hi requinix,

    Sorry about that, it uses Mail(). It uses a "for" clause to iterate the fields in the email. I want to format the email data I receive with say bold and underlines and maybe 2 columns and I know I have to use HTML but not sure how to incorporate into the FOR clause.

    Here is the whole script:

    PHP Code:
    <?php
    error_reporting
    (E_PARSE);
    define("ADMIN_MAIL""ADMINPREAPPSUB@.com");
    define("HOST_NAME"$_SERVER['HTTP_HOST']);
    define("PHP_SELF"$_SERVER['PHP_SELF']);
    define("ERR_MISSING""Missing required field : ");
    define("ERR_EMAIL""Please enter a valid e-mail address : ");
    define("ERR_CREDIT_CARD_NUMBER""Please check the credit card number : ");
    define("ERR_CREDIT_CARD_EXPIRED""Please check the credit card expiry date : ");
    define("ERR_SELECT_UPLOAD""Please select file : ");// recipient
     
    define("FORM_RECIPIENT""PREAPPSUB@.com");// This is the TO: staffer e-mail address! Is also FROM in 
    // auto e-mail to person submitting
    // --- Array of Form Elements ---


    $form_mail[] = array( "name" => "First_Name""text" => "First Name:",  "type" => "text""required" => "Required" ) ;

    $form_mail[] = array( "name" => "Middle_Name""text" => "Middle Name:",  "type" => "text""required" => "Required" ) ;

    $form_mail[] = array( "name" => "Last_Name""text" => "Last Name:",  "type" => "text""required" => "Required" ) ;


    // -- Detech Submit & SendMail --
    $isHideForm false;
    if( 
    $_POST["formmail_submit"] ){
        
    $sErr checkPass();
        if( ! 
    $sErr ){
            
    sendFormMail$form_mail"PREAPPSUBMISSION") ;
            
    $isHideForm true;

            
    $redirect "";
            if( 
    strlen(trim($redirect)) ):
                
    header"Location:$redirect);
                exit;
            endif;
        }
    }


    ?>
    <?
    // ===============================================
    function    sendFormMail$form_mail$sFileName ""  )
    {
        global    
    $_POST ;

        if (
    ereg('/freeformmaker.com/'HOST_NAME))
        {
            return;
        }
        
    $to FORM_RECIPIENT;
        
    $from "WebPreAppSubmission@" HOST_NAME//This is the FROM address for the submission 
        
    $subject $_POST["esh_formmail_subject"];

        
    // first stage keep it simple:
        
    $sWhatToDo $sFileName "mailandfile" "" //$_POST["esh_formmail_mail_and_file"];

        //$sFileName = $_POST["esh_formmail_save_record_file"];
        
    $cc $_POST["esh_formmail_cc"];
        
    $bcc $_POST["esh_formmail_bcc"];
        
    $charset $_POST["esh_formmail_charset"];

            
        for( 
    $i 0$i count$form_mail ); $i ++ ){
            
    $value trim$_POST$form_mail$i ][ "name" ] ] );
        
            
            
    $content .=$form_mail$i ][ "text" ] . ": \n" $value ."\n";
            
    $line .= remove_newline$value ) . "\t" ;
            if( 
    strtolower("Sender's email") == strtolower($form_mail$i ][ "type" ]) ) {
                
    //print "Type:[" . $form_mail[ $i ][ "type" ] . "] $value <br>\n";
                
    $from $value ;
            }
            
        };
        
        
    $content .= "\n\nIP:" getEnv"REMOTE_ADDR" );

        switch( 
    strtolower($sWhatToDo) ){
            case 
    "mailandfile" :
                
    mailAttachments$to $subject $content,  $from,  $charset$cc $bcc ) ;
                if( ! 
    appendToFile$sFileName$line ) )
                    
    mailReport$content "\n\nWrite Form Mail to File Fail." );
                break;

            case 
    "fileonly" :
                if( ! 
    appendToFile$sFileName$line ) )
                    
    mailReport$content "\n\nWrite Form Mail to File Fail."$from );
                break;

            default :
                
    mailAttachments$to $subject $content$from,  $charset$cc $bcc ) ;
        }

        
    mailAutoResponse$from ) ;
    }


    //------------------------------------------------------------------------------------------
    function mailAutoResponse$to ){
        global    
    $_POST ;
        
    $to $_POST["Email_Address"];
        
    $subject $_POST["esh_formmail_return_subject"];
        
    $responseMsg $_POST["esh_formmail_return_msg"];
        if( 
    $to && $responseMsg )
            
    mail$to$subject$responseMsg"From: " FORM_RECIPIENT);
    }


    //------------------------------------------------------------------------------------------
    function mailReport$content ""$from "" ){
        
    mailADMIN_MAIL"Error@" HOST_NAME PHP_SELF$content"From:$from);
    }

    //------------------------------------------------------------------------------------------
    function    remove_newline$str "" ){
        
    $newliner "<!--esh_newline-->" // replace \r\n with $newliner ;
        
    $newtaber "<!--esh_newtaber-->" // replace \t with $newtaber ;
        
    $str ereg_replace"\t"$newtaber$str );
        
    $str ereg_replace"\r\n"$newliner$str );
        return 
    ereg_replace"\n"$newliner$str );
    }

    //------------------------------------------------------------------------------------------
    function    checkPass()
    {
        global    
    $form_mail ;
        global    
    $_POST ;
        global    
    $HTTP_POST_FILES ;

        for( 
    $i 0$i count$form_mail ); $i ++ ){
            
    $type strtolower$form_mail$i ][ "type" ]  );
            
    $value trim$_POST$form_mail$i ][ "name" ] ] );
            
    $required $form_mail$i ][ "required" ] ;
            
    $text stripslashes$form_mail$i ][ "text" ] );

            
    // simple check the field has something keyed in.
            
    if( !strlen($value) && (  $required == "Required" ) && $type != "attachment" )
                return 
    ERR_MISSING $text  ;

            
    // verify the special case
            
    if(
                ( 
    strlen($value) || $type == "attachment" )
                &&  
    $required == "Required"
            
    ):
                switch( 
    $type ){
                        case     
    strtolower("Sender's Name") :
                                  break;
                        case     
    strtolower("Generic email"):
                        case     
    strtolower("Sender's email"):
                                   if( ! 
    formIsEMail($value) )     return ERR_EMAIL $text ;
                                   break;
                        case    
    "text" :
                                    break;
                        case     
    "textarea" :
                                    break;
                        case    
    "checkbox" :
                        case     
    "radio" :
                                    break;
                        case     
    "select" :
                                    break;
                        case     
    "attachment" :
                                    
    $upload_file $HTTP_POST_FILES$form_mail$i ]["name"] ][ "tmp_name" ] ;
                                    if( ! 
    is_uploaded_file($upload_file)  )
                                        return  
    ERR_SELECT_UPLOAD $text;
                                    break;
                        case 
    strtolower("Date(MM-DD-YYYY)"):
                                    break;
                        case 
    strtolower("Date(MM-YYYY)"):
                                    break;
                        case 
    strtolower("CreditCard(MM-YYYY)"):
                                    if( 
    $value date("Y-m") ) return ERR_CREDIT_CARD_EXPIRED  $text;
                                    break;
                        case 
    strtolower("CreditCard#"):
                                    if( !
    formIsCreditNumber$value )  ) return ERR_CREDIT_CARD_NUMBER  $text ;
                                    break;
                        case 
    strtolower("Time(HH:MM:SS)"):
                                    break;
                        case 
    strtolower("Time(HH:MM)"):
                                    break;
                        default :
                            
    //return $sErrRequired . $form_mail[ $i ][ "text" ];
                    
    // switch
            
    endif;
        } 
    // for

        
    return "" ;
    }



    //------------------------------------------------------------------------------------------
    function formSelected$var$val )
    {
        echo ( 
    $var == $val ) ? "selected" "";
    }


    //------------------------------------------------------------------------------------------
    function formChecked$var$val )
    {
        echo ( 
    $var == $val ) ? "checked" "";
    }


    //------------------------------------------------------------------------------------------
    function    formIsEMail$email ){
            return 
    ereg"^(.+)@(.+)\\.(.+)$"$email );
    }


    //------------------------------------------------------------------------------------------
    function    selectList$name$selectedValue$start$end$prompt "-Select-"$style "" )
    {
        
    $tab "\t" ;
        print 
    "<select name=\"$name\" $style>\n" ;
        print 
    $tab "<option value=''>$prompt</option>\n" ;
        
    $nLen strlen"$end) ;
        
    $prefix_zero str_repeat"0"$nLen );
        for( 
    $i $start$i <= $end $i ++ ){
            
    $stri substr$prefix_zero $istrlen($prefix_zero $i)-$nLen$nLen );
            
    $selected = ( $stri == $selectedValue ) ? " selected " "" ;
            print 
    $tab "<option value=\"$stri\" $selected >$stri</option>\n" ;
        }
        print 
    "</select>\n\n" ;
    }


    //------------------------------------------------------------------------------------------
    // something like CreditCard.pm in perl CPAN
    function formIsCreditNumber$number ) {

        
    $tmp $number;
        
    $number preg_replace"/[^0-9]/"""$tmp );

        if ( 
    preg_match(  "/[^\d\s]/"$number ) )  return 0;
        if ( 
    strlen($number) < 13  && 0+$number ) return 0;

        for (
    $i 0$i strlen($number) - 1$i++) {
            
    $weight substr($number, -* ($i 2), 1) * (- ($i 2));
            
    $sum += (($weight 10) ? $weight : ($weight 9));
        }

        if ( 
    substr($number, -1) == (10 $sum 10) % 10  )  return $number;
        return 
    $number;
    }


    // -------------------------- Begin Mail Attachment Functions -----------------------------------------------------------------
    function    mailAttachments$to "PREAPPSUB2@.com" $subject "" $message "" $from "PREAPPSUB@.com" $charset "iso-8859-1"$cc "" $bcc "" ){
        global    
    $HTTP_POST_FILES ;

            if( ! 
    strlentrim$to ) ) ) return "Missing \"To\" Field." ;

            
    $boundary "====_My_PHP_Form_Generator_" md5uniqidsrandtime() ) ) ) . "====";

            
    // setup mail header infomation
            
    $headers "From: $from\r\n";
            if (
    $cc$headers .= "CC: $cc\r\n";
            if (
    $bcc$headers .= "BCC: $bcc\r\n";
            
    $plainHeaders $headers // for no attachments header
            
    $headers .= "MIME-Version: 1.0\nContent-type: multipart/mixed;\n\tboundary=\"$boundary\"\n";

            
    $txtMsg "\nThis is a multi-part message in MIME format.\n" .
                            
    "\n--$boundary\n" .
                            
    "Content-Type: text/html;\n\tcharset=\"$charset\"\n\n"  $message "\n";

            
    //create mulitipart attachments boundary
            
    $sError "" ;
            
    $nFound 0;
            foreach( 
    $HTTP_POST_FILES as $aFile ){
                        
    $sFileName $aFile"tmp_name" ] ;
                        
    $sFileRealName $aFile"name" ] ;
                        if( 
    is_file$sFileName ) ):

                            if( 
    $fp fopen$sFileName"rb" ) ) :
                                
    $sContent fread$fpfilesize$sFileName ) );
                                
    $sFName basename$sFileRealName ) ;
                                
    $sMIME getMIMEType$sFName ) ;

                                
    $bPlainText = ( $sMIME == "text/html" ) ;
                                if( 
    $bPlainText ) :
                                    
    $encoding "" ;
                                else:
                                    
    $encoding "Content-Transfer-Encoding: base64\n";
                                    
    $sContent chunk_splitbase64_encode$sContent ) );
                                endif;

                                
    $sEncodeBody .=     "\n--$boundary\n" .
                                                            
    "Content-Type: $sMIME;\n" .
                                                            
    "\tname=\"$sFName\"\n" .
                                                            
    $encoding .
                                                            
    "Content-Disposition: attachment;\n" .
                                                            
    "\tfilename=\"$sFName\"\n\n" .
                                                            
    $sContent "\n" ;
                                
    $nFound ++;
                            else:
                                
    $sError .= "<br>File $sFileName can not open.\n" ;
                            endif; 
    // if( $fp = fopen( $sFileName, "rb" ) ) :

                        
    else:
                            
    $sError .= "<br>File $sFileName doesn't exist.\n" ;
                        endif; 
    //if( file_exists( $sFileName ) ):
            
    }; // end foreach

             
    $sEncodeBody .= "\n\n--$boundary--" ;
             
    $sSource $txtMsg $sEncodeBody ;


             
    $nFound mail$to$subject$sSource$headers  )
                            : 
    mail$to$subject$message$plainHeaders );

            return 
    $sError ;
    }

    /* ---------------------------------------------------------------------------------------------------
        Parameters: $sFileName
        Return :
            1. "" :  no extendsion name, or sFileName is empty
            2. string: MIME Type name of array aMimeType's definition.
       ---------------------------------------------------------------------------------------------------*/
    function    getMIMEType$sFileName "" ) {

            
    $sFileName strtolowertrim$sFileName ) );
            if( ! 
    strlen$sFileName  ) ) return "";

            
    $aMimeType = array(
                                            
    "txt" => "text/html" ,
                                            
    "pdf" => "application/pdf" ,
                                            
    "zip" => "application/x-compressed" ,

                                            
    "html" => "text/html" ,
                                            
    "htm" => "text/html" ,

                                            
    "avi" => "video/avi" ,
                                            
    "mpg" => "video/mpeg " ,
                                            
    "wav" => "audio/wav" ,

                                            
    "jpg" => "image/jpeg " ,
                                            
    "gif" => "image/gif" ,
                                            
    "tif" => "image/tiff " ,
                                            
    "png" => "image/x-png" ,
                                            
    "bmp" => "image/bmp"
                                        
    );
            
    $aFile split"\."basename$sFileName ) ) ;
            
    $nDiminson count$aFile ) ;
             
    $sExt $aFile$nDiminson ] ; // get last part: like ".tar.zip", return "zip"

            
    return ( $nDiminson ) ? $aMimeType$sExt ] : "";
    }
    // End Mail Attachment Functions


    //------------------------------------------------------------------------------------------
    function    appendToFile$sFileName ""$line "" ){
        if( !
    $sFileName || !$line ) return 0;
        
    $hFile fopen"$sFileName""a+w" );
        
    $nBytes 0;
        if( 
    $hFile ){
            
    $nBytes fputs$hFile trim($line)."\r\n" );
            
    fclose$hFile );
        };
        return 
    $nBytes ;
    }
    ?>
    Maybe I will have to get rid of the FOR clause and enter each value manually with $content or $message?

    I did change the content type to text/html where ever I found them.

    Sorry, I do not have a lot of PHP experience.

    Thanks,

    MP
  6. #4
  7. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,056
    Rep Power
    9398
    In mailAttachments() you have
    PHP Code:
    $plainHeaders $headers // for no attachments header 
    $plainHeaders is the set of mail headers used when there are no attachments. If there are attachments it will use $headers, and the email in that case does seem to be sent as HTML. The plain headers don't do that.

    So immediately after that line add
    PHP Code:
    $plainHeaders .= "Content-Type: text/html; charset=\"$charset\"\r\n"
    and see if that does it for you.
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    8
    Rep Power
    0
    Originally Posted by requinix
    In mailAttachments() you have
    PHP Code:
    $plainHeaders $headers // for no attachments header 
    $plainHeaders is the set of mail headers used when there are no attachments. If there are attachments it will use $headers, and the email in that case does seem to be sent as HTML. The plain headers don't do that.

    So immediately after that line add
    PHP Code:
    $plainHeaders .= "Content-Type: text/html; charset=\"$charset\"\r\n"
    and see if that does it for you.
    Requinix,

    Ok, I see how that could tell the script to use HTML, but where do I add my HTML tags in the "for" clause that actually controls the data being entered in the email?

    PHP Code:
    for( $i 0$i count$form_mail ); $i ++ ){
            
    $value trim$_POST$form_mail$i ][ "name" ] ] );
        
            
            
    $content .=$form_mail$i ][ "text" ] . ": \n" $value ."\n";
            
    $line .= remove_newline$value ) . "\t" ;
            if( 
    strtolower("Sender's email") == strtolower($form_mail$i ][ "type" ]) ) {
                
    //print "Type:[" . $form_mail[ $i ][ "type" ] . "] $value <br>\n";
                
    $from $value 

    Its the $content line and $value that control the actual data that shows up in the email. I need to add HTML tags here somewhere but don't know where.

    Thanks,

    MP
  10. #6
  11. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,056
    Rep Power
    9398
    To put a table in $content you'd have something like
    PHP Code:
    $content "<table>";
    // loop {
        
    $content .= "<tr><th>Field name here</th><td>{$value}</td></tr>\n";
    // }
    $content .= "</table>"
    It's basically the same as building an HTML table for a page, except you're putting it in a string.
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    8
    Rep Power
    0
    Requinix,

    I get these basics, bu i still do not now how to apply them to my FOR clause:

    I tried but can't get HTML tags to work to format my form fields which are the $form_mail vars.

    Should I scrap this FOR clause and just enter all my $form_mail vars manually with html tags around them?

    Thanks,



    PHP Code:
    //$sFileName = $_POST["esh_formmail_save_record_file"];
        
    $cc $_POST["esh_formmail_cc"];
        
    $bcc $_POST["esh_formmail_bcc"];
        
    $charset $_POST["esh_formmail_charset"];

            
        for( 
    $i 0$i count$form_mail ); $i ++ ){
            
    $value trim$_POST$form_mail$i ][ "name" ] ] );
        
            
    $content .=$form_mail$i ][ "text" ] . ": \n" $value ."\n";
            
            
            
    $line .= remove_newline$value ) . "\t" ;
            if( 
    strtolower("Sender's email") == strtolower($form_mail$i ][ "type" ]) ) {
                
    //print "Type:[" . $form_mail[ $i ][ "type" ] . "] $value <br>\n";
                
    $from $value ;
            }
            
        }; 
  14. #8
  15. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,056
    Rep Power
    9398
    Keep the for.

    You say you can't get it to work. So what have you tried? What I posted is pretty close to the final result you'll need.
  16. #9
  17. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    8
    Rep Power
    0
    Originally Posted by requinix
    Keep the for.

    You say you can't get it to work. So what have you tried? What I posted is pretty close to the final result you'll need.
    requinix,

    I have tried the following and the result is my very LAST form field shows up in the email in a table border with an underlined ":" in one column, and only the last form value in the next column and the form title above the form border along with the last line of $content .= "\n\nIPzz:" It is skipping all my other form fields.

    But I still have not formatted the ACTUAL FORM VALUES. How in the world do I format the "$value" inside a FOR iterative clause? If I mess with tags around ".$value.", it will not post the values.

    PHP Code:
    //$sFileName = $_POST["esh_formmail_save_record_file"];
        
    $cc $_POST["esh_formmail_cc"];
        
    $bcc $_POST["esh_formmail_bcc"];
        
    $charset $_POST["esh_formmail_charset"];

        for( 
    $i 0$i count$form_mail ); $i ++ ){
            
    $value trim$_POST$form_mail$i ][ "name" ] ] );
        
        
    $content '<html><body>';
        
    $content .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
            
            
        
    $content .=$form_mail$i ][ "text" ] . "<tr><td><u>: </u> </td><td>\n" $value ."</td></tr>\n";
            
                    
            
    $content .= "</table>";
            
    $content .= "</body></html>";
            
        
    //original for clause            
        //for( $i = 0; $i < count( $form_mail ); $i ++ ){
         //   $value = trim( $_POST[ $form_mail[ $i ][ "name" ] ] );
        
            //$content .=$form_mail[ $i ][ "text" ] . ": \n" . $value ."\n";
            
            
            
    $line .= remove_newline$value ) . "\t" ;
            if( 
    strtolower("Sender's email") == strtolower($form_mail$i ][ "type" ]) ) {
                
    //print "Type:[" . $form_mail[ $i ][ "type" ] . "] $value <br>\n";
                
    $from $value ;
            }
            
        };
        
        
    $content .= "\n\nIPzz:" getEnv"REMOTE_ADDR" ); 
    Thanks much,

    Mark
  18. #10
  19. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    8
    Rep Power
    0
    Hi,

    I finally got the table to work with the following. I had to get my </table> </body></html> etc lines in the right place and get the tags around my $form_mail var in the FOR clause.

    Thanks for all your help I really appreciate it!

    PHP Code:
    //$sFileName = $_POST["esh_formmail_save_record_file"];
        
    $cc $_POST["esh_formmail_cc"];
        
    $bcc $_POST["esh_formmail_bcc"];
        
    $charset $_POST["esh_formmail_charset"];

        
    $content '<html><body>';
        
    $content .= '<table rules="all" style="border-color: #666;" cellpadding="1">';
        
        for( 
    $i 0$i count$form_mail ); $i ++ ){
            
    $value trim$_POST$form_mail$i ][ "name" ] ] );
        
                    
            
    $content .="<tr><td align=right><font size=1><u>".$form_mail$i ][ "name" ].": </u></font></td><td><font size=1>\n<b>" $value ."</b></font></td></tr>\n";
            
                    
    //$content .=$form_mail[ $i ][ "text" ] . "<tr><td><u>".$form_mail[ $i ][ "name" ].": </u> //</td><td>\n" . $value ."</td></tr>\n";
            
            
        //original for clause            
        //for( $i = 0; $i < count( $form_mail ); $i ++ ){
         //   $value = trim( $_POST[ $form_mail[ $i ][ "name" ] ] );
        
            //$content .=$form_mail[ $i ][ "text" ] . ": \n" . $value ."\n";
            
            
            
    $line .= remove_newline$value ) . "\t" ;
            if( 
    strtolower("Sender's email") == strtolower($form_mail$i ][ "type" ]) ) {
                
    //print "Type:[" . $form_mail[ $i ][ "type" ] . "] $value <br>\n";
                
    $from $value ;
            }
            
        };
        
        
    $content .= "</table>";
        
    $content .= "</body></html>"

IMN logo majestic logo threadwatch logo seochat tools logo