php发展

首页 » 常识 » 预防 » 回顾使用PHP原生发送电子邮件终文件
TUhjnbcbe - 2025/7/21 17:02:00

FileAttachments

文件附件

Fileattachmentsworkjustlikemixedemail,exceptthatadifferentcontenttypeisusedforthemessageasawhole(multipart/mixedinsteadofmultipart/alternative),andthere’sanewContent-Dispositionheaderthattellstheemailclienthowtohandleeachpartofthemessage.

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

Let’swriteaPHPscriptthatprocessesaformsubmissionthatcontainsanemailmessagetobesent,possiblywithafileattachment,andsendsitout.I’lltalkyouthroughitlinebylinesothatbytheendyou’llnotonlyhaveausefulsnippetofPHPcode,butalsoanunderstandingofhowfileattachmentswork.Youcandownloadthescript(andtheformforit)ifyouwanttotryitoutforyourself.

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

First,wegrabthesubmittedvaluesandplacetheminPHPvariables.Mostpeoplehavetheirserverssetuptocreateglobalvariablesforsubmittedvaluesautomatically,butasofPHP4.1thisisnolongerthedefault,sowedoitbyhandjustincase.Sincewewanttoacceptfileattachments,it’ssafetoassumethattheformwillbesubmittedwithaPOSTrequest:

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

?php//ReadPOSTrequestparamsintoglobalvars$to=$_POST[to];$from=$_POST[from];$subject=$_POST[subject];$message=$_POST[message];FileuploadsinPHP4.1areplacedinaspecial$_FILESarray,sowefetchthevaluesweneedoutofit://Obtainfileuploadvars$fileatt=$_FILES[fileatt][tmp_name];$fileatt_type=$_FILES[fileatt][type];$fileatt_name=$_FILES[fileatt][name];$headers="From:$from";

Nextwecheckthe$fileattvariable,whichmayormaynotcontainthepathandfilenametoanuploadedfileattachment.WeusePHP’sis_uploaded_filefunctiontofindout:

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

if(is_uploaded_file($fileatt)){//Readthefiletobeattached(rb=readbinary)$file=fopen($fileatt,rb);$data=fread($file,filesize($fileatt));fclose($file);

Havingreadinthedataforthefileattachment,weneedtosetupthemessageheaderstosendamultipart/mixedmessage:

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

//Generateaboundarystring$semi_rand=md5(time());$mime_boundary="==Multipart_Boundary_x{$semi_rand}x";//Addtheheadersforafileattachment$headers.="nMIME-Version:1.0n"."Content-Type:multipart/mixed;n"."boundary="{$mime_boundary}"";

Nowforthemessagebodyitself.Thisworksjustaswesawforthetextpartofamixedmessageintheprevioussection:

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

//Addamultipartboundaryabovetheplainmessage$message="Thisisamulti-partmessageinMIMEformat.nn"."--{$mime_boundary}n"."Content-Type:text/plain;charset="iso--1"n"."Content-Transfer-Encoding:7bitnn".$message."nn";

Now,toallowforbinaryfiletypes,weneedtouseBase64encodingtoconvertthe(possiblybinary)fileattachmentdatatoatext-onlyformatsuitableforsendingbyemail.AllemailprogramsinpopularusesupportBase64encodingoffileattachments,sothisisthebestwaytogo.Fortunately,PHPprovidesafunctionforBase64encoding:

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

//Base64encodethefiledata

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

Wenowhaveeverythingweneedtowritetheportionofthemessagethatcontainsthefileattachment.Here’sthecode:

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

//Addfileattachmenttothemessage$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

1
查看完整版本: 回顾使用PHP原生发送电子邮件终文件