代码之家  ›  专栏  ›  技术社区  ›  Akash M

使用PHP在邮件中发送附件

  •  0
  • Akash M  · 技术社区  · 6 年前

    我想用PHP在邮件中发送文件附件。下面是我正在使用的代码,它正在工作,但每次执行循环时,邮件都会放在单独的附件中。

    /*Uploading docs Array*/
    $otherdoc_name = array($_FILES[ 'otherdoc' ][ 'name' ]);
    $otherdocCount = count( $_FILES[ 'otherdoc' ][ 'name' ]);         
    // print_r($otherdocCount); exit();
    for ( $i = 0; $i < $otherdocCount; $i++ ) {
        //Get the temp file path
        $tmpFilePath = $_FILES[ 'otherdoc' ][ 'tmp_name' ][ $i ];
        $i_names = $_FILES[ 'otherdoc' ][ 'name' ][ $i ];
        $i_sizes = $_FILES[ 'otherdoc' ][ 'size' ][ $i ];
        $i_errors = $_FILES[ 'otherdoc' ][ 'error' ][ $i ];
        $i_tmp_names = $_FILES[ 'otherdoc' ][ 'tmp_name' ][ $i ];
        $i_types = $_FILES[ 'otherdoc' ][ 'type' ][ $i ];
        $exts = pathinfo( $i_names, PATHINFO_EXTENSION );
        $msgs = '';
    
        if ( $i_errors == 0 ) {
            if ( $i_sizes > 0 ) {
                $otherdoc_name[$i] = rand() . '.' . $exts;
                $paths = $folder . $otherdoc_name[$i];
                $uploads = copy( $i_tmp_names, $paths );
                if ( $uploads ) {
                    $otherdoc_name[$i] = $otherdoc_name[$i];
                    /*Mail Function*/
                    if(isset($otherdoc_name))
                    {
                        $from_email         = 'my@domain.com'; //from mail, it is mandatory with some hosts
                        $recipient_email    = 'receiver@domain.com'; //recipient email (most cases it is your personal email)
    
                        //Capture POST data from HTML form and Sanitize them, 
                        $sender_name    = filter_var($_POST["sender_name"], FILTER_SANITIZE_STRING); //sender name
                        $reply_to_email = filter_var($_POST["sender_email"], FILTER_SANITIZE_STRING); //sender email used in "reply-to" header
                        $subject        = filter_var($_POST["subject"], FILTER_SANITIZE_STRING); //get subject from HTML form
                        $message        = filter_var($_POST["message"], FILTER_SANITIZE_STRING); //message
    
                        /* //don't forget to validate empty fields 
                        if(strlen($sender_name)<1){
                            die('Name is too short or empty!');
                        } 
                        */
    
                        //Get uploaded file data
                        $file_tmp_name    = $tmpFilePath;
                        $file_name        = $i_names;
                        $file_size        = $i_sizes;
                        $file_type        = $i_types;
                        $file_error       = $i_errors;
    
                        if($file_error > 0)
                        {
                            die('Upload error or No files uploaded');
                        }
                        //read from the uploaded file & base64_encode content for the mail
                        $handle = fopen($file_tmp_name, "r");
                        $content = fread($handle, $file_size);
                        fclose($handle);
                        $encoded_content = chunk_split(base64_encode($content));
    
                            $boundary = md5("sanwebe");
                            //header
                            $headers = "MIME-Version: 1.0\r\n"; 
                            $headers .= "From:".$from_email."\r\n"; 
                            $headers .= "Reply-To: ".$reply_to_email."" . "\r\n";
                            $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n"; 
    
                            //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: $file_type; name=".$file_name."\r\n";
                            $body .="Content-Disposition: attachment; filename=".$file_name."\r\n";
                            $body .="Content-Transfer-Encoding: base64\r\n";
                            $body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n"; 
                            $body .= $encoded_content; 
    
                        $sentMail = @mail($recipient_email, $subject, $body, $headers);
                        if($sentMail) //output success or failure messages
                        {       
                            echo 'Thank you for your email';
                        }else{
                            die('Could not send mail.');  
                        }
    
                    }
                    /* End Mail Function*/
                } else {
                    $otherdoc_name[$i] = '';
                }
    
            } else {
                $otherdoc_name[$i] = '';
            }
    
        } else {
            $otherdoc_name[$i] = '';
        }
    }
    

    我现在正在将此文件上载到一个文件夹中。我可以不直接上传而发送文件吗?

    我想所有文件都应该作为一封邮件发送。或者其他不同的逻辑建议。请帮帮我。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Synchro    6 年前

    请使用PHPMailer,这将很容易将其集成到您的应用程序中。

    从以下位置下载PHPMailer脚本: http://github.com/PHPMailer/PHPMailer

    提取存档并复制 src 将文件夹放置到项目中方便的位置。

    现在,发送带有附件的电子邮件非常简单:

    require 'phpmailer/src/PHPMailer.php';
    
    use PHPMailer\PHPMailer\PHPMailer;
    
    $email = new PHPMailer();
    $email->From      = 'you@example.com';
    $email->FromName  = 'Your Name';
    $email->Subject   = 'Message Subject';
    $email->Body      = $bodytext;
    $email->addAddress('destination@example.com');
    
    $email->addAttachment('PATH_TO_YOUR_FILE_HERE');
    
    return $email->send();
    

    只有一句话: $email->addAttachment();

        2
  •  0
  •   SRK    6 年前
        /*Uploading docs Array*/
        $otherdoc_name = array($_FILES[ 'otherdoc' ][ 'name' ]);
        $otherdocCount = count( $_FILES[ 'otherdoc' ][ 'name' ]);         
        $from_email         = 'my@domain.com'; //from mail, it is mandatory with some hosts
                            $recipient_email    = 'receiver@domain.com'; //recipient email (most cases it is your personal email)
    
                            //Capture POST data from HTML form and Sanitize them, 
                            $sender_name    = filter_var($_POST["sender_name"], FILTER_SANITIZE_STRING); //sender name
                            $reply_to_email = filter_var($_POST["sender_email"], FILTER_SANITIZE_STRING); //sender email used in "reply-to" header
                            $subject        = filter_var($_POST["subject"], FILTER_SANITIZE_STRING); //get subject from HTML form
                            $message        = filter_var($_POST["message"], FILTER_SANITIZE_STRING); //message
    $headers = "MIME-Version: 1.0\r\n"; 
        // print_r($otherdocCount); exit();
        for ( $i = 0; $i < $otherdocCount; $i++ ) {
            //Get the temp file path
            $tmpFilePath = $_FILES[ 'otherdoc' ][ 'tmp_name' ][ $i ];
            $i_names = $_FILES[ 'otherdoc' ][ 'name' ][ $i ];
            $i_sizes = $_FILES[ 'otherdoc' ][ 'size' ][ $i ];
            $i_errors = $_FILES[ 'otherdoc' ][ 'error' ][ $i ];
            $i_tmp_names = $_FILES[ 'otherdoc' ][ 'tmp_name' ][ $i ];
            $i_types = $_FILES[ 'otherdoc' ][ 'type' ][ $i ];
            $exts = pathinfo( $i_names, PATHINFO_EXTENSION );
            $msgs = '';
    
            if ( $i_errors == 0 ) {
                if ( $i_sizes > 0 ) {
                    $otherdoc_name[$i] = rand() . '.' . $exts;
                    $paths = $folder . $otherdoc_name[$i];
                    $uploads = copy( $i_tmp_names, $paths );
                    if ( $uploads ) {
                        $otherdoc_name[$i] = $otherdoc_name[$i];
                        /*Mail Function*/
                        if(isset($otherdoc_name))
                        {
    
    
                            /* //don't forget to validate empty fields 
                            if(strlen($sender_name)<1){
                                die('Name is too short or empty!');
                            } 
                            */
    
                            //Get uploaded file data
                            $file_tmp_name    = $tmpFilePath;
                            $file_name        = $i_names;
                            $file_size        = $i_sizes;
                            $file_type        = $i_types;
                            $file_error       = $i_errors;
    
                            if($file_error > 0)
                            {
                                die('Upload error or No files uploaded');
                            }
                            //read from the uploaded file & base64_encode content for the mail
                            $handle = fopen($file_tmp_name, "r");
                            $content = fread($handle, $file_size);
                            fclose($handle);
                            $encoded_content = chunk_split(base64_encode($content));
    
                                $boundary = md5("sanwebe");
                                //header
    
                                $headers .= "From:".$from_email."\r\n"; 
                                $headers .= "Reply-To: ".$reply_to_email."" . "\r\n";
                                $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n"; 
    
                                //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: $file_type; name=".$file_name."\r\n";
                                $body .="Content-Disposition: attachment; filename=".$file_name."\r\n";
                                $body .="Content-Transfer-Encoding: base64\r\n";
                                $body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n"; 
                                $body .= $encoded_content; 
    
    
                        }
                        /* End Mail Function*/
                    } else {
                        $otherdoc_name[$i] = '';
                    }
    
                } else {
                    $otherdoc_name[$i] = '';
                }
    
            } else {
                $otherdoc_name[$i] = '';
            }
        }
    
    $sentMail = @mail($recipient_email, $subject, $body, $headers);
                            if($sentMail) //output success or failure messages
                            {       
                                echo 'Thank you for your email';
                            }else{
                                die('Could not send mail.');  
                            }
    

    您可以简单地将邮件功能置于循环之外?尝试上述代码。请忽略语法错误,因为我没有测试它。但你可以遵循逻辑。

    使现代化

    核心PHP中的工作脚本,用于在一封邮件中发送多个附件。

    <?php
    /** Mail with attachment */
    function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $bcc, $subject, $message){    
        $uid = md5(uniqid(time()));
        $mime_boundary = "==Multipart_Boundary_x{$uid}x"; 
    
        $header = "From: ".$from_name." <".$from_mail.">\r\n";
        $header .= "Bcc: ".$bcc."\r\n";
        $header .= "Reply-To: ".$replyto."\r\n";
        $header .= "MIME-Version: 1.0\r\n";
        $header .= "Content-Type: multipart/mixed; boundary=\"".$mime_boundary."\"\r\n\r\n";
        $header .= "This is a multi-part message in MIME format.\r\n";
        $header .= "--".$mime_boundary."\r\n";
        $header .= "Content-type:text/html; charset=iso-8859-1\r\n";
        $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
        $header .= nl2br($message)."\r\n\r\n";
        $header .= "--".$mime_boundary."\r\n";
    
        foreach($filename as $k=>$v){
    
            $file = $path.$v;
            $file_size = filesize($file);
            $handle = fopen($file, "r");
            $content = fread($handle, $file_size);
            fclose($handle);
            $content = chunk_split(base64_encode($content));
    
            $header .= "Content-Type: application/octet-stream; name=\"".$v."\"\r\n"; // use different content types here
            $header .= "Content-Transfer-Encoding: base64\r\n";
            $header .= "Content-Disposition: attachment; filename=\"".$v."\"\r\n\r\n";
            $header .= $content."\r\n\r\n";
            $header .= "--".$mime_boundary."--"."\r\n";
        } 
    
        if (mail($mailto, $subject, "", $header)) {
            //echo "mail send ... OK"; // or use booleans here
            return true;
        } else {
            //echo "mail send ... ERROR!";
            return false;
        }
    }
    ?>