Php – How to send an base64 image on a mail body with PHP

base64emailimagePHP

I'm trying to send an email with an image in base64 on the body with PHP using the code below, but the image never appears… If I change to an URL it works, but it doesn't with the base64… I tested the base64 on a new page only with <img src=base64> and worked too… What am I missing??

<?php
    // recipients
    $to  = $_POST['email'];

    // subject
    $subject = 'Test';

    // message
    $message = '
        <html>
        <head>
         <title>Test</title>
        </head>
        <body>

            <img src="'.$_POST['imageFromOtherPage'].'"/>

        </body>
        </html>
        ';

    // To send HTML mail, the Content-type header must be set
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

    // Mail it
    mail($to, $subject, $message, $headers);
 ?>

Here is my base64 image example: http://jsfiddle.net/28nP4/

Best Answer

I tried different things and the only way I found was uploading the image and getting the URL, I got that from this link: http://j-query.blogspot.in/2011/02/save-base64-encoded-canvas-image-to-png.html

It is very simple:

<?php
    // requires php5
    define('UPLOAD_DIR', 'images/');
    $img = $_POST['img'];
    $img = str_replace('data:image/png;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    $file = UPLOAD_DIR . uniqid() . '.png';
    $success = file_put_contents($file, $data);
    print $success ? $file : 'Unable to save the file.';
?>

And this generates an URL, so, instead of using <img src="'.$_POST['imageFromOtherPage'].'"/>, I use the generated URL. Worked perfectly!