Search code examples
phphtmlfilephpmailer

Send attachments in Mail using PHP


I want to send file attachments in mail using PHP. Below is code I am using which is working but each time loop gets executed the mails are going in separate attachments.

/*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         = '[email protected]'; //from mail, it is mandatory with some hosts
                    $recipient_email    = '[email protected]'; //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] = '';
    }
}

I am uploading this files to one folder at present now. Can I send files without uploading directly ?

I want all files should be sent as one mail. Or any other different logic suggestions for me. Please help me out.


Solution

  • Please use PHPMailer, that would be really easy to integrate it into your application.

    Download the PHPMailer script from here: http://github.com/PHPMailer/PHPMailer

    Extract the archive and copy the src folder to a convenient place in your project.

    Now, sending emails with attachments incredibly easy:

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

    It's just that one line: $email->addAttachment();