繁体   English   中英

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

[英]How can I send an email with attachments from a PHP form?

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

正如其他人在回答中所建议的那样,最好使用现有工具。 但是,如果您想自己动手或只是了解方式,请继续阅读。

HTML

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

  • 您的表单需要具有以下属性: enctype="multipart/form-data"
  • 您至少需要一个字段,例如<input type="file" name="examplefile"> 这允许用户浏览要附加的文件。

如果您同时拥有这两个文件浏览器将上传所有附加文件以及表单提交

旁注:这些文件将作为临时文件保存在服务器上。 对于此示例,我们将获取其数据并通过电子邮件发送,但是如果将临时文件移动到永久位置,则只需创建一个文件上传表单。

MIME电子邮件格式

本教程非常适合了解如何在PHP中构建MIME电子邮件(其中可以包含HTML内容,纯文本版本,附件等)。 我以它为起点。

基本上,您要做三件事:

  • 预先声明此电子邮件中将包含多种内容
  • 声明将用于分隔不同部分的文本字符串
  • 定义每个部分并坚持适当的内容。 对于文件附件,必须指定类型并以ASCII编码。
    • 每个部分将具有content-type例如image/jpgapplication/pdf. 更多信息可以在这里找到。 (我的示例脚本使用内置的PHP函数从每个文件中提取此信息。)

的PHP

提交表单后,浏览器上载的所有文件(请参见HTML部分)都可以通过$_FILES变量获得,该变量包含“通过HTTP POST方法上载到当前脚本的项目的关联数组”。

$_FILES上的文档比较糟糕,但是上载后,您可以运行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有一些限制附件大小的设置。 有关更多信息,请参见此讨论

PHP函数示例

我创建了以下函数,该函数可以包含在页面中,并用于收集与表单一起提交的所有文件附件。 随意使用它和/或使其适应您的需求。

总附件限制是任意的,但是大量附件可能会使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()的调用,并使其回显输出到屏幕。

为了发送实际的电子邮件,我建议使用PHPMailer库 ,它使一切变得更加容易。

不错的教程在这里

代码

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

您可能要签出SwiftMailer 它对此有一个很好的教程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM