如何从PHP表单发送带附件的电子邮件?
答案 0 :(得分:12)
最好使用现有工具,正如其他人在答案中所建议的那样。但是,如果您想自己动手或只是了解方法,请继续阅读。
HTML中只有两个要求用于发送文件附件。
enctype="multipart/form-data"
<input type="file" name="examplefile">
这样的字段。这允许用户浏览要附加的文件。如果您同时拥有这两项,浏览器将上传所有附加文件以及表单提交。
旁注:这些文件在服务器上保存为临时文件。对于此示例,我们将获取他们的数据并通过电子邮件发送,但如果您将临时文件移动到永久位置,则您刚刚创建了一个文件上载表单。
This tutorial非常适合理解如何在PHP中构建MIME电子邮件(可以包含HTML内容,纯文本版本,附件等)。我用它作为起点。
基本上,你做了三件事:
content-type
,例如image/jpg
或application/pdf.
可以找到更多信息here。 (我的示例脚本使用内置的PHP函数从每个文件中提取此信息。)提交表单后,浏览器上传的任何文件(请参阅HTML部分)都可以通过$_FILES
变量获得,该变量包含'通过HTTP POST上传到当前脚本的关联数组项方法。'
$_FILES
上的documentation很糟糕,但上传后,您可以运行print_r($_FILES)
查看其工作原理。它将输出如下内容:
Array ( [examplefile] => Array ( [name] => your_filename.txt
[type] => text/plain [tmp_name] =>
C:\path\to\tmp\file\something.tmp [error] => 0 [size] => 200 ) )
然后,您可以使用file_get_contents($_FILES['examplefile']['tmp_name'])
获取相关临时文件中的数据。
php.ini
有一些限制附件大小的设置。有关详细信息,请参阅this discussion。
我创建了以下功能,该功能可以包含在页面上,用于收集随表单提交的任何文件附件。随意使用和/或根据您的需要进行调整。
总附件限制是任意的,但是大量可能会使mail()
脚本陷入困境或被发送或接收电子邮件服务器拒绝。做自己的测试。
(注意:PHP中的mail()
函数取决于php.ini
中了解如何发送电子邮件的信息。)
function sendWithAttachments($to, $subject, $htmlMessage){
$maxTotalAttachments=2097152; //Maximum of 2 MB total attachments, in bytes
$boundary_text = "anyRandomStringOfCharactersThatIsUnlikelyToAppearInEmail";
$boundary = "--".$boundary_text."\r\n";
$boundary_last = "--".$boundary_text."--\r\n";
//Build up the list of attachments,
//getting a total size and adding boundaries as needed
$emailAttachments = "";
$totalAttachmentSize = 0;
foreach ($_FILES as $file) {
//In case some file inputs are left blank - ignore them
if ($file['error'] == 0 && $file['size'] > 0){
$fileContents = file_get_contents($file['tmp_name']);
$totalAttachmentSize += $file['size']; //size in bytes
$emailAttachments .= "Content-Type: "
.$file['type'] . "; name=\"" . basename($file['name']) . "\"\r\n"
."Content-Transfer-Encoding: base64\r\n"
."Content-disposition: attachment; filename=\""
.basename($file['name']) . "\"\r\n"
."\r\n"
//Convert the file's binary info into ASCII characters
.chunk_split(base64_encode($fileContents))
.$boundary;
}
}
//Now all the attachment data is ready to insert into the email body.
//If the file was too big for PHP, it may show as having 0 size
if ($totalAttachmentSize == 0) {
echo "Message not sent. Either no file was attached, or it was bigger than PHP is configured to accept.";
}
//Now make sure it doesn't exceed this function's specified limit:
else if ($totalAttachmentSize>$maxTotalAttachments) {
echo "Message not sent. Total attachments can't exceed " . $maxTotalAttachments . " bytes.";
}
//Everything is OK - let's build up the email
else {
$headers = "From: yourserver@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n"
."Content-Type: multipart/mixed; boundary=\"$boundary_text\"" . "\r\n";
$body .="If you can see this, your email client "
."doesn't accept MIME types!\r\n"
.$boundary;
//Insert the attachment information we built up above.
//Each of those attachments ends in a regular boundary string
$body .= $emailAttachments;
$body .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n"
."Content-Transfer-Encoding: 7bit\r\n\r\n"
//Inert the HTML message body you passed into this function
.$htmlMessage . "\r\n"
//This section ends in a terminating boundary string - meaning
//"that was the last section, we're done"
.$boundary_last;
if(mail($to, $subject, $body, $headers))
{
echo "<h2>Thanks!</h2>Form submitted to " . $to . "<br />";
} else {
echo 'Error - mail not sent.';
}
}
}
如果你想看看这里发生了什么,请注释掉mail()
的号码,然后将输出反映到你的屏幕上。
答案 1 :(得分:2)
为了发送实际的电子邮件,我建议使用PHPMailer library,这会让一切变得更加轻松。
答案 2 :(得分:1)
代码
<?php
//define the receiver of the email
$to = 'youraddress@example.com';
//define the subject of the email
$subject = 'Test email with attachment';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>--
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--
<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
答案 3 :(得分:1)
您可能想查看SwiftMailer。它有一个很好的tutorial on this。