Search code examples
wordpresscontact-form-7

How to send HTML content in message body using contact form 7?


I want to send HTML content using contact form 7, but HTML code is not work direct send HTML tag in email. so how can I send this type of message using the hook or any way ?

I want to send HTML content using contact form 7, but HTML code is not working direct send HTML tag in email. so how can I send this type of message using the hook or any way?

I am using hook "wpcf7_posted_data" to append my extra HTML tag in body text. I want to send extra HTML format data before send an email.

function action_wpcf7_posted_data( $array ) {
    $html .= '<table>';
    $html .='<tr><td>'.$product->get_Name().'</td></tr>';
    $html .='<tr><td>'.$display.'</td></tr>';
    $html .='<tr><td>Qty : '.$ProductQty.'</td></tr>';
    $html .= '</table>';
    $value = $array['message'];
    if( !empty( $value ) ){       
        $array['message'] = $value."<br><br>".$html;
    }
    return $array;
}
add_filter( 'wpcf7_posted_data', 'action_wpcf7_posted_data', 10, 1 );

Solution

  • If you are trying to append data to the Contact Form 7 email HTML. The below code will do that. However, it appears that you're using some other variables that I wasn't sure where you were getting them from. All of the submitted form fields will be in $posted_data in my function below. You can trigger the process on the existence of a field, or just run it every time. You can also use global $product and get variables to complete your table.

    add_action( 'wpcf7_before_send_mail', 'he_append_to_email_body' );
    function he_append_to_email_body( $contact_form ) {
    
        $submission = WPCF7_Submission::get_instance();
            if ( $submission ) {
                $posted_data = $submission->get_posted_data();    
        }
    
        if (isset($posted_data['the_field_you_want_to_trigger_this'])) { // Check that your field is present in your form.
            /**
             * ToDo:
             * Get your product and display and other variables here to put into the table.
             */
            $html = '<table>';
            $html .='<tr><td>'.$product->get_Name().'</td></tr>';
            $html .='<tr><td>'.$display.'</td></tr>';
            $html .='<tr><td>Qty : '.$ProductQty.'</td></tr>';
            $html .= '</table>';
            // Get the existing output from the CF7 email
            $mail = $contact_form->prop( 'mail' );
            // Append your data after the existing
            $mail['body'] .= $html;
            // Update the mail 
            $contact_form->set_properties(array('mail' => $mail));
        }
        return;
    }