您的位置 首页 php

回顾使用PHP原生发送电子邮件(终)文件附件

File Attachments

文件附件

File attachments work just like mixed email, except that a different content type is used for the message as a whole (multipart/mixed instead of multipart/alternative), and there’s a new Content-Disposition header that tells the email client how to handle each part of the message.

文件附件的工作原理与混合电子邮件类似,不同的是,邮件作为一个整体使用不同的内容类型(多部分/混合而不是多部分/替代),并且有一个新的内容处理头,告诉电子邮件客户端如何处理邮件的每个部分。

Let’s write a PHP script that processes a form submission that contains an email message to be sent, possibly with a file attachment, and sends it out. I’ll talk you through it line by line so that by the end you’ll not only have a useful snippet of PHP code, but also an understanding of how file attachments work. You can download the script (and the form for it) if you want to try it out for yourself.

让我们编写一个PHP脚本来处理表单提交,表单提交包含要发送的电子邮件(可能带有文件附件),并将其发送出去。我将一行一行地告诉您,这样到最后,您不仅可以获得有用的PHP代码片段,还可以了解文件附件是如何工作的。如果您想亲自尝试,可以下载脚本(及其表单)。

First, we grab the submitted values and place them in PHP variables. Most people have their servers set up to create global variables for submitted values automatically, but as of PHP 4.1 this is no longer the default, so we do it by hand just in case. Since we want to accept file attachments, it’s safe to assume that the form will be submitted with a POST request:

首先,我们获取提交的值并将它们放入PHP变量中。大多数人的服务器设置为自动为提交的值创建全局变量,但从PHP4.1开始,这不再是默认值,所以我们手工操作以防万一。由于我们希望接受文件附件,因此可以安全地假设表单将随POST请求一起提交:

 <?php
// Read POST request params into global vars
$to      = $_POST['to'];
$from    = $_POST['from'];
$subject = $_POST['subject'];
$message = $_POST['message'];
File uploads in PHP 4.1 are placed in a special $_FILES array, so we fetch the values we need out of it:

// Obtain file upload vars
$fileatt      = $_FILES['fileatt']['tmp_name'];
$fileatt_type = $_FILES['fileatt']['type'];
$fileatt_name = $_FILES['fileatt']['name'];
$headers = "From: $from";  

Next we check the $fileatt variable, which may or may not contain the path and filename to an uploaded file attachment. We use PHP’s is_uploaded_file function to find out:

接下来我们检查$fileatt变量,它可能包含也可能不包含上传文件附件的路径和文件名。我们使用PHP的is_upload_file函数来查找:

 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);  

Having read in the data for the file attachment, we need to set up the message headers to send a multipart/mixed message:

读入文件附件的数据后,我们需要设置消息头以发送多部分/混合消息:

  // 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.0n" .
"Content-Type: multipart/mixed;n" .
" boundary="{$mime_boundary}"";  

Now for the message body itself. This works just as we saw for the text part of a mixed message in the previous section:

现在来看消息体本身。正如我们在上一节中看到的混合消息的文本部分一样:

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

Now, to allow for binary file types, we need to use Base64 encoding to convert the (possibly binary) file attachment data to a text-only format suitable for sending by email. All email programs in popular use support Base64 encoding of file attachments, so this is the best way to go. Fortunately, PHP provides a function for Base64 encoding:

现在,为了允许二进制文件类型,我们需要使用Base64编码将(可能是二进制的)文件附件数据转换为适合通过电子邮件发送的纯文本格式。所有流行的电子邮件程序都支持文件附件的Base64编码,因此这是最好的方法。幸运的是,PHP为Base64编码提供了一个函数:

// Base64 encode the file data

$data = chunk_split(base64_encode($data));

We now have everything we need to write the portion of the message that contains the file attachment. Here’s the code:

现在,我们已经具备了编写包含文件附件的消息部分所需的一切。代码如下:

  // 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: base64nn" .
$data . "nn" .
"--{$mime_boundary}--n";
}  

That completes the modifications necessary to accommodate a file attachment. We can now send the message with a quick call to mail:

这就完成了容纳文件附件所需的修改。我们现在可以通过快速呼叫邮件发送消息:

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

And that’s how we send emails with file attachments in PHP!

这就是我们用PHP发送带有文件附件的电子邮件的方式!

Summary

总结

In this article, you probably learned a lot more about email than you ever wanted to know. That intimate knowledge about what makes email tick allowed us to do some pretty special things with PHP’s deceptively simple mail function.

在这篇文章中,你可能学到了比你想知道的更多的关于电子邮件的知识。通过对电子邮件产生原因的深入了解,我们可以利用PHP看似简单的邮件功能做一些非常特别的事情。

文章来源:智云一二三科技

文章标题:回顾使用PHP原生发送电子邮件(终)文件附件

文章地址:https://www.zhihuclub.com/78859.shtml

关于作者: 智云科技

热门文章

评论已关闭

1条评论

  1. Pretty section off content. I just stumbled upon your web
    site and in accession capital to assert that I acquire
    actually enjoyed acxcount your blog posts.
    Anyway I will be subscribing to your augment and even I achievement you access consistently fast.

    My web page:

网站地图