MrVimes
MrVimes

Reputation: 3312

Is there an alternative method for sending email attachments in php?

I have some code in a php file that sends an attachment (an excel file that was generated by the same php script) by email.

Every tested client - IOS (iphone 3gs, 4, 4s, ipad, ipad2), Android (Icecream Sandwich), Blackberry, Microsoft Outlook 2007 (on XP) reads the email and the attachment absolutely fine, but the actual person we send the email to gets a message with lots of characters and no attachment. It's as if his email server (he's on a domain so not a known email service like hotmail or gmail) is failing to interpret the sent bytes and see that some of it is an attachment.

The snippet of code I use is as follows...

function email($recipients,$filename,$subject,$cc,$bcc){

    $to = $recipients;
    $subject = "EWS-".$subject;
    $random_hash = md5(date('r', time()));



    if($cc <> ""){
        $header_cc = "\r\nCc: ".$cc;

    }else{
        $header_cc = "";
    }

    if($bcc <> ""){
        $header_bcc = "\r\nBcc: ".$bcc;

    }else{
        $header_bcc = "";
    }


    $headers = "From: [email protected]\r\nReply-To: [email protected]". $header_cc . $header_bcc;
    $headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
    $attachment = chunk_split(base64_encode(file_get_contents($filename)));
    ob_start(); 

    ?>

--PHP-mixed-<?php echo $random_hash; ?> 
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"

--PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit


--PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit


--PHP-alt-<?php echo $random_hash; ?>--

--PHP-mixed-<?php echo $random_hash; ?> 
Content-Type: application/excel; name="<?php echo $filename ?>"
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

<?php echo $attachment; ?>

--PHP-mixed-<?php echo $random_hash; ?>--

    <?php

    $message = ob_get_clean();
    $mail_sent = @mail( $to, $subject, $message, $headers );
    return $mail_sent ? "Mail sent" : "Mail failed"; 

}

The customer gets the email like this (it was forwaded back to us so I'm viewing it in Outlook)...

Sample of what is being received by the recipient

Upvotes: 0

Views: 1269

Answers (1)

thenetimp
thenetimp

Reputation: 9820

There are lots of class files that have this functionality built in why re-create the wheel?

Upvotes: 1

Related Questions