Contact Form 7升级后无法附加动态生成的TXT文件至邮件
解决Contact Form 7 7.5.4+版本无法附加动态生成文件到邮件的问题
问题原因
Contact Form 7在7.5.4版本后,将WPCF7_Submission类中的add_uploaded_file方法改为私有,导致原代码中直接调用该方法添加附件的逻辑失效。虽然动态生成的.txt文件已在服务器正确创建,但无法被注入到邮件附件列表中。
解决方案
改用CF7官方支持的wpcf7_mail_components过滤器,在邮件发送流程中直接修改附件数组,将动态生成的文件添加进去。这种方式无需依赖私有方法,符合CF7的升级规范。
修正后的代码示例
add_action( 'wpcf7_before_send_mail', 'CF7_pre_sender' ); function CF7_pre_sender($cf7) { $formid = $_POST['_wpcf7']; global $date_stamp; if($formid === '4436'): // 生成txt内容 $output = ""; $output .= $_POST['your-message'] . '|' . $_POST['your-address'] . '|||' . $_POST['your-city'] . '||' . $_POST['your-post-code'] . '||' . $_POST['your-name'] . '|' . $_POST['your-name'] . '||' . $_POST['your-email'] . '||' . $_POST['your-telephone'] . '|' . $_POST['your-telephone'] . '||True|True||' . $_POST['model'] . '||' . $_POST['SN'] . '|2020-10-17T12:00:00.000Z||' . $date_stamp . '|' ; // 使用wp_upload_dir()存放文件,避免权限问题 $upload_dir = wp_upload_dir(); $file_path = $upload_dir['path'] . '/' . $date_stamp . ".txt"; file_put_contents($file_path, $output); // 将文件路径存储到CF7对象中,供后续过滤器调用 $cf7->set_prop('custom_attachment', $file_path); endif; }; // 通过过滤器添加自定义附件 add_filter( 'wpcf7_mail_components', 'CF7_add_custom_attachment', 10, 3 ); function CF7_add_custom_attachment( $components, $form, $mail ) { $custom_file = $form->get_prop('custom_attachment'); if ( $custom_file && file_exists($custom_file) && is_readable($custom_file) ) { // 初始化附件数组(若为空) if ( empty($components['attachments']) ) { $components['attachments'] = array(); } $components['attachments'][] = $custom_file; } return $components; }
额外优化建议
处理完邮件发送后,可添加代码删除临时生成的.txt文件,避免服务器存储冗余:
add_action( 'wpcf7_mail_sent', 'CF7_cleanup_temp_file' ); function CF7_cleanup_temp_file($cf7) { $custom_file = $cf7->get_prop('custom_attachment'); if ( $custom_file && file_exists($custom_file) ) { unlink($custom_file); } }
内容的提问来源于stack exchange,提问作者bronco888
相关产品推荐
相关产品推荐

