将文件动态附加到 Contact Form 7 电子邮件

Dynamically attaching file to Contact Form 7 E-Mail

我在 WordPress 中使用 Contact Form 7。我正在根据用户提交的数据动态创建一个 Word 文档,我想将该文件附加到用户从 Contact 发送的电子邮件中表格 7。

为了确认,文件已创建并保存在正确的位置。我的问题肯定是将它附加到来自 CF7 的电子邮件中。

我现在有以下代码:

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))
                   return;


               // 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;

           }
        }
    }

一切正常,直到 $submission->add_uploaded_file('docx', $upload_dir . $fileName);

相关文档不多,但我读到我需要包含类似于以下内容的内容:

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;
}

(来源:https://wordpress.stackexchange.com/questions/239579/attaching-a-pdf-to-contact-form-7-e-mail-via-functions-php

为了让附件显示出来。但是,我不知道如何获得我需要的特定文件,因为该文件对于每次提交都是唯一的,并且所有变量都将在一个单独的函数中。

修复了这个问题。

我补充了:

// make file variable global
  global $CV_file;
  $CV_file = $upload_dir . $fileName;

$submission->add_uploaded_file('docx', $upload_dir . $fileName);之后

然后与 add_action 分开,我使用了过滤器并引用了全局变量:

add_filter( 'wpcf7_mail_components', 'mycustom_wpcf7_mail_components' );
    function mycustom_wpcf7_mail_components( $components ) {
        global $CV_file;
        $components['attachments'][] = $CV_file;
        return $components;
    }

这是可行的解决方案:

add_filter('wpcf7_mail_components', 'custom_wpcf7_mail_components');
    function custom_wpcf7_mail_components($components)
    {
        //Get current form
        $wpcf7 = WPCF7_ContactForm::get_current();
        $attachment_file_path = '';
        //check the relevant form id
        if ($wpcf7->id == '30830') {
            // get current SUBMISSION instance
            $submission = WPCF7_Submission::get_instance();
            if ($submission) {
                // get submission data
                $data = $submission->get_posted_data();
                // setup upload directory
                $upload_dir = wp_upload_dir();
                if (isset($data['file_name']) && !empty($data['file_name'])) {
                    /*
                    * Form hidden attachment file name Ex: 'ProRail_NA_Gen5.pdf'
                    * You can hard-code the file name or set file name to hidden form field using JavaScript
                    */
                    $file_name = $data['file_name'];
                    //get upload base dir path Ex: {path}/html/app/uploads
                    $base_dir = $upload_dir['basedir'];
                    //file uploaded folder
                    $file_dir = 'download';
                    //set attachment full path
                    $attachment_file_path = $base_dir .'/'.$file_dir.'/'.$file_name;
                    //append new file to mail attachments
                    $components['attachments'][] = $attachment_file_path;
                }
            }
        }
        return $components;
    }

我将留下一个完整示例,使用 wpcf7_before_send_mail 创建和存储 PDF 并使用 wpcf7_mail_components 将其附加到电子邮件中。
使用 FPDF.

创建的 PDF
<?php
/**
 * Plugin Name: Create and attach PDF to CF7 email
 * Author: brasofilo
 * Plugin URL: 
 */

!defined('ABSPATH') && exit;

require_once('fpdf/fpdf.php');

add_action('plugins_loaded', array(SendFormAttachment::get_instance(), 'plugin_setup'));

class SendFormAttachment {
    protected static $instance = NULL;
    public $formID = 5067; # YOUR ID
    public $theFile = false;

    public function __construct() { }

    public static function get_instance() {
        NULL === self::$instance and self::$instance = new self;
        return self::$instance;
    }

    public function plugin_setup() {
        add_action('wpcf7_before_send_mail', function ( $contact_form, $abort, $submission ) {
            if ($contact_form->id() == $this->formID) {
                $posted_data = $submission->get_posted_data();
                $uploads = wp_upload_dir();
                $the_path = $uploads['basedir'] . '/cf7_pdf/';
                $fname = $this->createPDF($posted_data, $the_path);
                $this->theFile = $the_path . $fname;
            }
        }, 10, 3);

        add_filter( 'wpcf7_mail_components', function( $components ) {
            if( $this->theFile )
                $components['attachments'][] = $this->theFile;
            return $components;
        });
    }

    public function createPDF($posted_data, $savepath) {
        $pdf = new FPDF();
        $pdf->AliasNbPages();
        $pdf->AddPage();
        $pdf->SetFont('Times','',12);
        $pdf->SetCreator('example.com');
        $pdf->SetAuthor('Author name', true);
        $pdf->SetTitle('The title', true);
        $pdf->SetSubject('The subject', true);
        for($i=1;$i<=40;$i++)
            $pdf->Cell(0,10,'Printing line number '.$i,0,1);

        $filename = rand() . '_' . time() . '.pdf';
        $pdf->Output('F', $savepath . $filename);
        return $filename;
    }
}