📜  PHP |用电子邮件发送附件

📅  最后修改于: 2022-05-13 01:56:54.942000             🧑  作者: Mango

PHP |用电子邮件发送附件

发送电子邮件是 Web 浏览器中非常常见的活动。例如,当新用户加入网络时发送电子邮件、发送时事通讯、发送问候邮件、发送发票。我们可以使用内置的mail()函数以编程方式发送电子邮件。此函数需要三个必需的参数,它们包含有关收件人、消息主题和消息正文的信息。除了这三个必需参数之外,还有两个可选参数。其中一个是标头,另一个是参数。
我们已经在之前的文章中讨论过使用PHP发送基于文本的电子邮件。在本文中,我们将了解如何使用 mail()函数发送带有附件的电子邮件。
当调用 mail()函数时, PHP将尝试立即将邮件发送给收件人,然后在成功发送邮件时返回 true,如果发生错误则返回 false。
语法

bool mail( $to, $subject, $message, $headers, $parameters );

以下是每个参数的说明。

NameDescriptionRequired/OptionalType
toThis contains the receiver or receivers of the particular emailRequiredString
subjectThis contains the subject of the email. This parameter cannot contain any newline charactersRequiredString
messageThis contains the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters (We will use wordwrap() function to achieve this.)RequiredString
headersThis contains additional headers, like From, Cc, Mime Version, Bcc.OptionalString
parametersSpecifies an additional parameter to the send mail programOptionalString

当我们通过PHP发送邮件时,邮件中的所有内容将仅被视为简单文本。如果我们在邮件正文中放置任何 HTML 标记,它不会被格式化为 HTML 语法。 HTML 标记将显示为简单文本。
要根据 HTML 语法格式化任何 HTML 标记,我们可以指定消息正文的MIME(多用途 Internet 邮件扩展)版本、内容类型和字符集
要将附件与电子邮件一起发送,我们需要将Content-type设置为混合/多部分,并且我们必须在Boundary中定义文本和附件部分。
创建一个 HTML 表单

html
                             


php
if($_POST['button'] && isset($_FILES['attachment']))
{
 
    $from_email         = 'sender@abc.com'; //from mail, sender email address
    $recipient_email    = 'recipient@xyz.com'; //recipient email address
     
    //Load POST data from HTML form
    $sender_name    = $_POST["sender_name"] //sender name
    $reply_to_email = $_POST["sender_email"] //sender email, it will be used in "reply-to" header
    $subject        = $_POST["subject"] //subject for the email
    $message        = $_POST["message"] //body of the email
     
 
    /*Always remember to validate the form fields like this
    if(strlen($sender_name)<1)
    {
        die('Name is too short or empty!');
    }
    */
     
    //Get uploaded file data using $_FILES array
    $tmp_name    = $_FILES['my_file']['tmp_name']; // get the temporary file name of the file on the server
    $name        = $_FILES['my_file']['name'];  // get the name of the file
    $size        = $_FILES['my_file']['size'];  // get size of the file for size validation
    $type        = $_FILES['my_file']['type'];  // get type of the file
    $error       = $_FILES['my_file']['error']; // get the error (if any)
 
    //validate form field for attaching the file
    if($file_error > 0)
    {
        die('Upload error or No files uploaded');
    }
 
    //read from the uploaded file & base64_encode content
    $handle = fopen($tmp_name, "r");  // set the file handle only for reading the file
    $content = fread($handle, $size); // reading the file
    fclose($handle);                  // close upon completion
 
    $encoded_content = chunk_split(base64_encode($content));
 
    $boundary = md5("random"); // define boundary with a md5 hashed value
 
    //header
    $headers = "MIME-Version: 1.0\r\n"; // Defining the MIME version
    $headers .= "From:".$from_email."\r\n"; // Sender Email
    $headers .= "Reply-To: ".$reply_to_email."\r\n"; // Email address to reach back
    $headers .= "Content-Type: multipart/mixed;"; // Defining Content-Type
    $headers .= "boundary = $boundary\r\n"; //Defining the Boundary
         
    //plain text
    $body = "--$boundary\r\n";
    $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
    $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
    $body .= chunk_split(base64_encode($message));
         
    //attachment
    $body .= "--$boundary\r\n";
    $body .="Content-Type: $type; name=".$name."\r\n";
    $body .="Content-Disposition: attachment; filename=".$name."\r\n";
    $body .="Content-Transfer-Encoding: base64\r\n";
    $body .="X-Attachment-Id: ".rand(1000, 99999)."\r\n\r\n";
    $body .= $encoded_content; // Attaching the encoded file with email
     
    $sentMailResult = mail($recipient_email, $subject, $body, $headers);
 
    if($sentMailResult )
    {
       echo "File Sent Successfully.";
       unlink($name); // delete the file after attachment sent.
    }
    else
    {
       die("Sorry but the email could not be sent.
                    Please go back and try again!");
    }
}


用于处理表单数据的PHP脚本

PHP

if($_POST['button'] && isset($_FILES['attachment']))
{
 
    $from_email         = 'sender@abc.com'; //from mail, sender email address
    $recipient_email    = 'recipient@xyz.com'; //recipient email address
     
    //Load POST data from HTML form
    $sender_name    = $_POST["sender_name"] //sender name
    $reply_to_email = $_POST["sender_email"] //sender email, it will be used in "reply-to" header
    $subject        = $_POST["subject"] //subject for the email
    $message        = $_POST["message"] //body of the email
     
 
    /*Always remember to validate the form fields like this
    if(strlen($sender_name)<1)
    {
        die('Name is too short or empty!');
    }
    */
     
    //Get uploaded file data using $_FILES array
    $tmp_name    = $_FILES['my_file']['tmp_name']; // get the temporary file name of the file on the server
    $name        = $_FILES['my_file']['name'];  // get the name of the file
    $size        = $_FILES['my_file']['size'];  // get size of the file for size validation
    $type        = $_FILES['my_file']['type'];  // get type of the file
    $error       = $_FILES['my_file']['error']; // get the error (if any)
 
    //validate form field for attaching the file
    if($file_error > 0)
    {
        die('Upload error or No files uploaded');
    }
 
    //read from the uploaded file & base64_encode content
    $handle = fopen($tmp_name, "r");  // set the file handle only for reading the file
    $content = fread($handle, $size); // reading the file
    fclose($handle);                  // close upon completion
 
    $encoded_content = chunk_split(base64_encode($content));
 
    $boundary = md5("random"); // define boundary with a md5 hashed value
 
    //header
    $headers = "MIME-Version: 1.0\r\n"; // Defining the MIME version
    $headers .= "From:".$from_email."\r\n"; // Sender Email
    $headers .= "Reply-To: ".$reply_to_email."\r\n"; // Email address to reach back
    $headers .= "Content-Type: multipart/mixed;"; // Defining Content-Type
    $headers .= "boundary = $boundary\r\n"; //Defining the Boundary
         
    //plain text
    $body = "--$boundary\r\n";
    $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
    $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
    $body .= chunk_split(base64_encode($message));
         
    //attachment
    $body .= "--$boundary\r\n";
    $body .="Content-Type: $type; name=".$name."\r\n";
    $body .="Content-Disposition: attachment; filename=".$name."\r\n";
    $body .="Content-Transfer-Encoding: base64\r\n";
    $body .="X-Attachment-Id: ".rand(1000, 99999)."\r\n\r\n";
    $body .= $encoded_content; // Attaching the encoded file with email
     
    $sentMailResult = mail($recipient_email, $subject, $body, $headers);
 
    if($sentMailResult )
    {
       echo "File Sent Successfully.";
       unlink($name); // delete the file after attachment sent.
    }
    else
    {
       die("Sorry but the email could not be sent.
                    Please go back and try again!");
    }
}

PHP是一种专门为 Web 开发而设计的服务器端脚本语言。您可以按照此PHP教程和PHP示例从头开始学习PHP 。