Export Form Data to a CSV then send it as an attachment – contact form 7

There are a few things omitted in the above solution, like defining the most params of wp_mail.
Also I didn’t want to send yet another concurrent email, but instead attach the csv directly to the mail that wpcf7 sends. I think this is the cleaner solution.

Here’s my take:

add_filter( 'wpcf7_before_send_mail', 'add_form_as_attachment', 10, 3 );
function add_form_as_attachment( $contact_form, $abort, $submission ) {

    $form_id = $contact_form->id();

    //Check for selected form id and actual submission
    if ($form_id == 123 && $submission){

        $posted_data = $submission->get_posted_data() ;
        // Check again for posted data
        if ( empty ($posted_data)){
            return; 
        }

        //Get your form fields
        $firstname = $posted_data['your-name'];
        $lastname = $posted_data['your-lastname'];
        $email = $posted_data['your-email'];

        $list = array (
        array( 'First Name:',$firstname),
        array( 'Last Name:', $lastname),
        array( 'Email:',  $email),

        );
        // Save file path separately 
        $upload_dir = wp_upload_dir(); 
        $file_path = $upload_dir['basedir'].'/yourtempfolder/sample.csv'; // check File permission for writing content and remember to protect this folder from the public with htaccess for example

        $fp = fopen( $file_path , 'w'); //overwrites file at each submission
        foreach ($list as $fields) {
            fputcsv($fp, $fields);
        }
        fclose($fp);

        // Modification of mail(1) start here
        $properties = $contact_form->get_properties();
        $properties['mail']['attachments'] = $file_path;
        $contact_form->set_properties($properties);

        return $contact_form;
    }//endif ID && submission
}