Sending email with multiple attachment using PhP

phpMail

The posted below PhP code (function) can be used to send an email with multiple attachment using PhP.

========= =========== =========

<?php

$attch1=/attach/file1.txt

$attach2=/attach/file2.txt

$thefiles[0]=”$attch1″;

$thefiles[1]=”$attch2″;

$to = “destination@domain.com”;

$subject = “Hello”;

$message = “How are you”;

$senderEmail = “origin@domain.com”;

$senderName = “My Name”;

function multi_attach_mail($to, $subject, $message, $senderEmail, $senderName, $thefiles){
    $from = $senderName.” <“.$senderEmail.”>”;
    $headers = “From: $from”;
    ## boundary
    $semi_rand = md5(time());
    $mime_boundary = “==Multipart_Boundary_x{$semi_rand}x”;
    ## headers for attachment
    $headers .= “\nMIME-Version: 1.0\n” . “Content-Type: multipart/mixed;\n” . ” boundary=\”{$mime_boundary}\””;
    ## multipart boundary
    $message = “–{$mime_boundary}\n” . “Content-Type: text/html; charset=\”UTF-8\”\n” .
    “Content-Transfer-Encoding: 7bit\n\n” . $message . “\n\n”;
    ## preparing attachments
    if(count($thefiles) > 0){
        for($i=0;$i<count($thefiles);$i++){
            if(is_file($thefiles[$i])){
                $message .= “–{$mime_boundary}\n”;
                $fp =    @fopen($thefiles[$i],”rb”);
                $data =  @fread($fp,filesize($thefiles[$i]));
                @fclose($fp);
                $data = chunk_split(base64_encode($data));
                $message .= “Content-Type: application/octet-stream; name=\””.basename($thefiles[$i]).”\”\n” .
                “Content-Description: “.basename($thefiles[$i]).”\n” .
                “Content-Disposition: attachment;\n” . ” filename=\””.basename($thefiles[$i]).”\”; size=”.filesize($thefiles[$i]).”;\n” .
                “Content-Transfer-Encoding: base64\n\n” . $data . “\n\n”;
            }
        }
    }
    $message .= “–{$mime_boundary}–“;
    $returnpath = “-f” . $senderEmail;
    ##send email
    $mail = @mail($to, $subject, $message, $headers, $returnpath);
    ##function return true, if email sent, otherwise return fasle
    if($mail){ return TRUE; } else { return FALSE; }
}
?>