从PHP表单上传和发送附件

时间:2014-02-10 05:31:07

标签: php

尝试在表单上使用最简单的文件上载方法,并将文件作为附件发送到我的电子邮件中。只需要这张照片。这已成为一场噩梦,我一直在网上无休止地搜索,并且有太多广泛的PHP编码让我失望。非常感谢任何帮助或建议。表格提交成功,我收到了电子邮件,但没有附件!请指出我在这里做错了什么?

这是简单的HTML。

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<form action="sendit.php" method="post" name="mainform" enctype="multipart/form-data">
Name
<br />
<input name="name" type="text">

<br />

Email
<br />
<input name="email" type="text">

<br />
Attach File
<input name="photofile" type="file">

<br />
<br />
<input type="submit" name="Submit" value="Send">

</form>
</body>
</html>

这是可爱的PHP。

<html>
<head>
<title> Sending Email </title>
</head>
<body>
<?php
// Variables
$name    = $_POST['name'];
$email    = $_POST['email'];

$to  = 'info@thebrlab.com' . ', ';
$to .= $Email; 
$subject = 'This Is Becoming A Headache';

// Obtain file upload vars
$fileatt      = $_FILES['fileatt']['tmp_name'];
$fileatt_type = $_FILES['fileatt']['type'];
$fileatt_name = $_FILES['fileatt']['name'];


if (is_uploaded_file($fileatt)) {
// Read the file to be attached ('rb' = read binary)
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);

// Generate a boundary string
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

// Add the headers for a file attachment
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";

// Add a multipart boundary above the plain message
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";

// Base64 encode the file data
$data = chunk_split(base64_encode($data));

// Add file attachment to the message
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
}

// Additional Headers
$headers = "From: $name <$email>\r\n";
$headers .= "X-Priority: 3\r\n";
$headers .= "Return-Path: ".$name." <".$email.">\r\n";
$headers .= "Reply-to: ".$name." <".$email.">\r\n";
$headers .= "Content-type: text/html\r\n";
$to = "$to";

// Send the message
$ok = @mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>Mail sent! Yay PHP!</p>";
} else {
echo "<p>Mail could not be sent. Sorry!</p>";
}
?>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

您在下面的行中覆盖了之前的headers

$headers = "From: $name <$email>\r\n";
      //^------- You need to add the concatenate operator as shown in the below code.

应该是

$headers .= "From: $name <$email>\r\n";

答案 1 :(得分:0)

这可能会有所帮助...... Send attachments with PHP Mail()?

如果我真正理解你在寻找什么,那就更好了...... http://www.excellentwebworld.com/send-file-in-email-attachment-on-form-submit-using-php/