如何从PHP表单发送带有附件的电子邮件?

如何从PHP表单发送带有附件的电子邮件?,php,email,attachment,Php,Email,Attachment,如何从PHP表单发送带有附件的电子邮件?可能最好使用现有工具,正如其他人在回答中所建议的那样。然而,如果你想自己动手,或者只是想知道怎么做,那就继续阅读吧 HTML 在HTML中,发送文件附件实际上只有两个要求 您的表单需要具有以下属性:enctype=“多部分/表单数据” 您至少需要一个类似的字段。这允许用户浏览要附加的文件 如果您同时拥有这两个文件,浏览器将随表单提交一起上载任何附加文件 旁注:这些文件保存为服务器上的临时文件。在本例中,我们将获取他们的数据并通过电子邮件发送给他们,但如

如何从PHP表单发送带有附件的电子邮件?

可能最好使用现有工具,正如其他人在回答中所建议的那样。然而,如果你想自己动手,或者只是想知道怎么做,那就继续阅读吧

HTML 在HTML中,发送文件附件实际上只有两个要求

  • 您的表单需要具有以下属性:
    enctype=“多部分/表单数据”
  • 您至少需要一个类似
    的字段。这允许用户浏览要附加的文件
如果您同时拥有这两个文件,浏览器将随表单提交一起上载任何附加文件

旁注:这些文件保存为服务器上的临时文件。在本例中,我们将获取他们的数据并通过电子邮件发送给他们,但如果您将临时文件移动到永久位置,则您刚刚创建了一个文件上载表单

MIME电子邮件格式 非常有助于理解如何用PHP构建MIME电子邮件(可以包含HTML内容、纯文本版本、附件等)。我以此为出发点

基本上,你要做三件事:

  • 提前声明此电子邮件将包含多种类型的内容
  • 声明用于分隔不同部分的文本字符串
  • 定义每个部分并插入适当的内容。对于文件附件,必须指定类型并用ASCII编码。
    • 每个部分都有一个
      内容类型
      ,例如
      图像/jpg
      应用程序/pdf。
      可以找到更多信息。(我的示例脚本使用内置PHP函数从每个文件中提取此信息。)
PHP 提交表单后,通过
$\u files
变量可以使用浏览器上载的任何文件(参见HTML部分),该变量包含“通过HTTP POST方法上载到当前脚本的项目的关联数组”

$\u文件
上的文件很糟糕,但是上传后,您可以运行
打印($\u文件)
来查看它的工作原理。它将输出如下内容:

Array ( [examplefile] => Array ( [name] => your_filename.txt 
[type] => text/plain [tmp_name] => 
C:\path\to\tmp\file\something.tmp [error] => 0 [size] => 200 ) ) 
然后,您可以使用
file\u get\u内容($\u FILES['examplefile']['tmp\u name'])
获取相关临时文件中的数据

关于文件大小限制的旁注
php.ini
有一些限制附件大小的设置。有关更多信息,请参阅

一个PHP函数示例 我创建了以下函数,该函数可以包含在页面上,用于收集随表单提交的任何文件附件。请随意使用和/或根据您的需要进行调整

总附件限制是任意的,但是大量附件可能会使
mail()
脚本陷入困境,或者被发送或接收电子邮件的服务器拒绝。自己做测试

(注意:PHP中的
mail()
函数取决于
PHP.ini
中的信息,以了解如何发送电子邮件。)

函数带附件发送($to、$subject、$htmlMessage){
$maxTotalAttachments=2097152;//附件总数最多为2MB,以字节为单位
$boundary\u text=“任何不可能出现的随机字符串字符”;
$boundary=“-->$boundary\U text”。\r\n”;
$boundary\u last=“-->$boundary\u text.”--\r\n;
//建立附件列表,
//获取总大小并根据需要添加边界
$emailAttachments=“”;
$totalAttachmentSize=0;
foreach($\u文件为$file){
//如果某些文件输入留空,请忽略它们
如果($file['error']==0&&$file['size']>0){
$fileContents=file_get_contents($file['tmp_name']);
$totalAttachmentSize+=$file['size'];//大小(字节)
$emailAttachments.=“内容类型:”
.$file['type']。“name=\”.basename($file['name'])。“\”\r\n
“内容传输编码:base64\r\n”
“内容处置:附件;文件名=\”“
.basename($file['name'])。“\”\r\n
.“\r\n”
//将文件的二进制信息转换为ASCII字符
.chunk_split(base64_编码($fileContents))
.$边界;
}
}
//现在,所有附件数据都已准备好插入电子邮件正文。
//如果文件对于PHP来说太大,它可能会显示为0大小
如果($totalAttachmentSize==0){
echo“未发送消息。可能未附加任何文件,或者该文件比PHP配置为接受的文件大。”;
}
//现在确保它不超过此函数的指定限制:
else if($totalAttachmentSize>$maxTotalAttachments){
echo“邮件未发送。附件总数不能超过“$maxTotalAttachments.”字节;
}
//一切都很好-让我们建立电子邮件
否则{
$headers=“From:yourserver@example.com\r\n“;
$headers.=“MIME版本:1.0\r\n”
“内容类型:多部分/混合;边界=\”$boundary\u text\”。“\r\n”;
$body.=“如果您可以看到此内容,您的电子邮件客户端”
“不接受MIME类型!\r\n”
.$边界;
//插入我们在上面建立的附件信息。
//这些附件中的每一个都以规则的边界字符串结尾
$body.=$emailAttachments;
$body.=“内容类型:text/html;字符集=\“iso-8859-1\”\r\n”
“内容传输编码:7比特\r\n\r\n”
//将传递给此函数的HTML消息体设置为惰性
.$htmlMessage。“\r\n”
//本节以终止边界字符串结尾-表示
//“这是最后一部分,我们完成了”
.$boundary_last;
if(邮件($to、$subject、$body、$headers))
{
echo“谢谢!表格已提交至“$to”。
”; }否则{ 回显“错误-未发送邮件”; } } }
如果您想查看这里发生了什么,请注释掉对
mail()
的调用,并让它将输出回送到您的屏幕上。

很好

代码

<?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";
?> 

--PHP混合-
内容类型:多部分/备选;boundary=“PHP alt-”
--PHP alt-
内容类型:文本/纯文本;charset=“iso-8859-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";
?>