我想导出表单数据并将其作为附件发送。在这种情况下,我可以用表单数据重写文件(/uploads/2020/08/sample.csv)并将其作为附件发送吗。
现在,当我在电子邮件中收到它时,它只是一个空白附件
这是我的函数代码。php,请帮助我:
add_action( \'wpcf7_before_send_mail\', \'add_form_as_attachment\', 10, 1 );
function add_form_as_attachment(&$WPCF7_ContactForm) {
$contact_form = WPCF7_ContactForm::get_current();
$Fname = $formdata[\'firstName\'];
$Lname = $formdata[\'lastName\'];
$email = $formdata[\'email\'];
$list = array (
array( \'First Name:\',$Fname),
array( \'Last Name:\', $Lname),
array( \'Email:\', $email),
);
$fp = fopen( site_url() . \'uploads/2020/08/sample.csv\', \'w\');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
}
SO网友:JTjards
上述解决方案中省略了一些内容,例如定义wp\\u mail的大多数参数。此外,我不想再发送另一封并发电子邮件,而是将csv直接附加到wpcf7发送的邮件中。我认为这是更干净的解决方案。
以下是我的看法:
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
}
SO网友:amitdutt24
我用这个代码解决了我的问题。希望它也能帮助别人-
add_action( \'wpcf7_before_send_mail\', \'add_form_as_attachment\', 10, 1 );
function add_form_as_attachment(&$WPCF7_ContactForm) {
$contact_form = WPCF7_ContactForm::get_current();
$Fname = $formdata[\'firstName\'];
$Lname = $formdata[\'lastName\'];
$email = $formdata[\'email\'];
$list = array (
array( \'First Name:\',$Fname),
array( \'Last Name:\', $Lname),
array( \'Email:\', $email),
);
// Save file path separately
$file_path = site_url() . \'uploads/2020/08/sample.csv\'; // check File permission for writing content
$fp = fopen( $file_path , \'w\');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
//MAIL starts here
$attachments = array( $file_path );
$headers = \'From: name <[email protected]>\' . "\\r\\n";
wp_mail($to, $subject, $message,$headers, $attachments);
// You are done
}