如何使用 php 将文档附加到电子邮件中


How to attach a document to an email using php

我的网站目录中有一个文档,我想在单击提交按钮时将其附加到电子邮件中,但是在使其工作时遇到问题,我不太明白如何在没有错误的情况下执行此操作。这就是我目前所拥有的。

$message = "Body Test";
$attachment = $myFile=fopen("DATA/EmailDoc.txt","r") or exit("Can't open file!"); fclose($myFile);
    if (isset($_POST['submit'])){
        mail('sulmaxcp@gmail.com', 'Subject Test', $message);
    }

使用PHP的原生mail函数,这是可行的,但非常困难。您需要自己实现邮件的多部分协议(需要在正文中指定其他标头和编码附件)。

下面是多部分邮件的外观示例(取自 RFC)

 From: Nathaniel Borenstein <nsb@bellcore.com> 
 To:  Ned Freed <ned@innosoft.com> 
 Subject: Sample message 
 MIME-Version: 1.0 
 Content-type: multipart/mixed; boundary="simple 
 boundary" 
 This is the preamble.  It is to be ignored, though it 
 is a handy place for mail composers to include an 
 explanatory note to non-MIME compliant readers. 
 --simple boundary 
 This is implicitly typed plain ASCII text. 
 It does NOT end with a linebreak. 
 --simple boundary 
 Content-type: text/plain; charset=us-ascii 
 This is explicitly typed plain ASCII text. 
 It DOES end with a linebreak. 
 --simple boundary-- 
 This is the epilogue.  It is also to be ignored.

这意味着,您首先需要将特定的 Content-Type 标头传递给邮件,其中边界值指定邮件中所有部分之间的分隔符(通常您将有两个部分:邮件的实际内容和附件)。

然后在邮件正文中,您需要有一个包含所有这些部分的字符串,如上面的示例所示。如果您想附加二进制文件,事情会更加复杂,因为这样您可能需要对这些二进制图像进行 base64 编码,并将使用的编码添加到已编码的部件标头中。

总结一下:如果你想要附件,不要使用 php mail 函数,而是使用 PHPMailer 这样的工具,它会更高级、更易于使用。

使用 PHPMailer 类,以便您可以附加需要发送的文件和所需的其他项目。