Dynamically attaching file to Contact Form 7 E-Mail


Staff member
I'm working in WordPress with Contact Form 7. I'm dynamically creating a Word Document based on the users submitted data, and I want to attach that file to the e-mail that the user is sent from Contact Form 7.

To confirm, the file is created and saved in the correct location. My issue is definitely with attaching it to the e-mail from CF7.

I have the following code at the moment:

add_action('wpcf7_before_send_mail', 'cv_word_doc');  
    function cv_word_doc($WPCF7_ContactForm) {

        // Check we're on the CV Writer (212)
        if ( $WPCF7_ContactForm->id() === 212 ) {

            //Get current form
            $wpcf7 = WPCF7_ContactForm::get_current();

            // get current SUBMISSION instance
            $submission = WPCF7_Submission::get_instance();

            if ($submission) {

                // get submission data
                $data = $submission->get_posted_data();

                // nothing's here... do nothing...
                if (empty($data))

               // collect info to add to word doc, removed for brevity...

               // setup upload directory and name the file
               $upload_dir = wp_upload_dir();
               $upload_dir = $upload_dir['basedir'] . '/cv/';
               $fileName = 'cv-' . str_replace(' ', '-', strtolower($firstName)) . '-' . str_replace(' ', '-', strtolower($lastName)) .'-'. time() .'.docx';

              // PHPWord stuff, removed for brevity...

              // save the doc 
              $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
              $objWriter->save($upload_dir . $fileName);

              // add upload to e-mail
              $submission->add_uploaded_file('docx', $upload_dir . $fileName);

              // carry on with cf7
              return $wpcf7;


Everything works up until
$submission->add_uploaded_file('docx', $upload_dir . $fileName);

There's not much documentation about, but I have read that I need to include something similar to:

add_filter( 'wpcf7_mail_components', 'mycustom_wpcf7_mail_components' );

function mycustom_wpcf7_mail_components( $components ) {
    $components['attachments'][] = 'full path of your PDF file';

    return $components;

(source: <a href="https://wordpress.stackexchange.com...df-to-contact-form-7-e-mail-via-functions-php">https://wordpress.stackexchange.com...df-to-contact-form-7-e-mail-via-functions-php</a>)

In order to get the attachment to show. However, I don't know how I can get the specific file that I need, as the file is unique to each submission and all of the variables will be in a separate function.