wp_mail() - 正在发送'文件'输入类型从表单作为附件

时间:2017-04-21 19:00:47

标签: php wordpress forms email html-email

我有短代码,可以在我的fucntions.php文件中创建和验证表单。提交并验证表单后,数据将存储在SESSION变量中。 SESSION变量用于将信息传递到自定义PHP模板页面。此页面使用wp_mail()通过电子邮件发送表单数据并显示感谢信。

我的问题是该表单有一个'文件'图像上传的输入类型。我已正确验证,但转移上传的图片,然后通过电子邮件将其作为' $附件"在wp_mail()函数中我正在努力解决这个问题。

另外我知道我应该将上传的图像保存在临时文件夹中,而不是将其存储在SESSION变量中。然后我将只需要在发送电子邮件后删除图像。

我的问题是如何?所有这些的代码都很长,所以这里有简短的版本:

functions.php(在短代码函数中)

<?php
$file = "";
$fileErr = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

   //file upload is required, make sure its not empty
   if(empty($_FILES['pmFile'])){
       $fileErr = "This is required!";
   }
   else{
       $file = $_FILES['pmFile'];//I validate here, but lets just say its OK     
   } 

   //If the error message is empty, store data in SESSION variables, and 
   //uploaded file in temp folder + redirect to thank you page
   if(empty($fileErr)){

      //HOW DO I SAVE THE FILE TEMPORARILY FOR USE ON THE NEXT PAGE??? 

      wp_redirect( '../wp-content/themes/rest of the path/thankYouPage.php' );
      exit();

   }else{ /*display errors*/}

}

//down here is where I wrote the code for the form. YES method=post, YES I 
//included enctype="multipart/form-data, YES the file input name is in fact 
//'pmFile'.
?>

thankYouPage.php

//initial page stuff 
//start email setup
$to = 'XXXXX@gmail.com';

$email_from = 'XXXXX@gmail.com';
$email_subject = "New Price Match Request";
$email_body = "I display the html and data here";

//for attachments
//HOW DO I PULL THAT UPLOADED FILE FROM THE TEMP FOLDER AND SEND IT AS AN ATTACHMENT?
$attachments = (the file in temp folder);
//NOW HOW TO I DELETE IT FROM THE TEMP FOLDER

$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email \r\n"; //$email is a SESSION variable pulled from before
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

//set to html
add_filter('wp_mail_content_type',create_function('', 'return "text/html"; '));

//send
wp_mail( $to, $email_subject, $email_body, $headers, $attachments );

// Reset content-type to avoid conflicts
remove_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );

我知道它删除了很多代码,但是电子邮件适用于SESSION变量传输的表单中的所有其他信息。我真的只需要知道如何传输这个上传的文件并通过电子邮件发送。谢谢!

2 个答案:

答案 0 :(得分:1)

如果我理解正确......

要从临时文件夹上传文件,请使用move_uploaded_filewp_handle_upload

然后将文件附加到邮件$attachments = array( WP_CONTENT_DIR . '/uploads/file.txt' );

使用unlink发送邮件并删除。

答案 1 :(得分:0)

我只是使用PHPMailer,它非常简单并且有很好的文档,发送附件也很容易。