我有一个php代码( example.php )从以下表单中提取电子邮件ID (sender@example.com),获取上传文件和发送电子邮件到 recipient@example.com ,已上传文件为附件和已解压缩的电子邮件id为发件人ID 。然后将用户重定向到 success.html 页面。
html表格如下:
<form action="http://example.com/example.php" enctype="multipart/form-data" method="POST">
<label>Your Email <input name="sender_email" type="email" /> </label></p>
<label>Attachment <input name="my_file" type="file" /></label> <label><input name="button" type="submit" value="Submit" /></label></p>
</form>
<p>
</p>
表单的php是:
<?php
if($_POST && isset($_FILES['my_file']))
{
$recipient_email = 'recipient@example.com';
//Capture POST data from HTML form and Sanitize them,
$from_email = filter_var($_POST["sender_email"],
FILTER_SANITIZE_STRING); //sender email used in "reply-to" header
$subject = SUBMISSION_PG;
$message = filter_var($_POST["message"],
FILTER_SANITIZE_STRING); //message
//Get uploaded file data
$file_tmp_name = $_FILES['my_file']['tmp_name'];
$file_name = $_FILES['my_file']['name'];
$file_size = $_FILES['my_file']['size'];
$file_type = $_FILES['my_file']['type'];
$file_error = $_FILES['my_file']['error'];
if($file_error > 0)
{
die('Upload error or No files uploaded');
}
//read from the uploaded file & base64_encode content for the mail
$handle = fopen($file_tmp_name, "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content));
$boundary = md5("sanwebe");
//header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:".$from_email."\r\n";
$headers .= "Reply-To: ".$from_email."" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary =
$boundary\r\n\r\n";
//plain text
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($message));
//attachment
$body .= "--$boundary\r\n";
$body .="Content-Type: $file_type; name=".$file_name."\r\n";
$body .="Content-Disposition: attachment;
filename=".$file_name."\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$body .= $encoded_content;
$sentMail = @mail($recipient_email, $subject, $body, $headers);
if($sentMail) //output success or failure messages
{
header("Location:http://example.com/success.html");
}else{
die('Could not send mail! Please check your PHP mail
configuration.');
}
}
?>
我需要将上传的文件名重命名为 sender@example.com.extension ,然后将上传的文件作为附件发送。
我会感谢任何可以解决这个问题的人。
答案 0 :(得分:0)
在此答案中找到:https://stackoverflow.com/a/31428803/2311317
在这一行:
$body .="Content-Type: $file_type; name=".$file_name."\r\n";
更改为
$body .= "Content-Type: application/octet-stream; name=\"".$file_name."\"\r\n";
不要忘记在这些行和其他放置PHP变量的行中转义双引号。
喜欢这种情况:
name=\"".$file_name."\"\r\n"
注意额外的报价和转义报价。