How can I send an base64 image on a mail body with PHP?

18,849

Solution 1

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!

Solution 2

i have the same problem, and finaly i resolved it. It might be helpful for you: You can use SwiftMailer, but you must to add new Image TextHeader 'Content-Location'. Here is the code:

$message = \Swift_Message::newInstance()->setSubject($subject)->setFrom($fromEmail, 'Name')->setTo($toEmail)->setBcc($bccEmails);
/*get uniqueID from cid:uniqueID */
$imageID = explode(':', $message->embed(\Swift_Image::fromPath('pathToTheImage')->setContentType('image/png')))[1];

/*Add Content-Location to image header*/
/** @var \Swift_Image $image */
$image = $message->getChildren()[0];
$image->getHeaders()->addTextHeader('Content-Location', $imageID);
$message->setBody('here you will have some html with <img src=$imageID alt="Embed Image">', 'text/html');

$mailer->send($message);

Solution 3

function for get all images url :

function getImagesFromMsg($msg, $tmpFolderPath)
{
    $arrSrc = array();
    if (!empty($msg))
    {
        preg_match_all('/<img[^>]+>/i', stripcslashes($msg), $imgTags);

        //All img tags
        for ($i=0; $i < count($imgTags[0]); $i++)
        {
            preg_match('/src="([^"]+)/i', $imgTags[0][$i], $withSrc);
            //Remove src
            $withoutSrc = str_ireplace('src="', '', $withSrc[0]);

            //data:image/png;base64,
            if (strpos($withoutSrc, ";base64,"))
            {
                //data:image/png;base64,.....
                list($type, $data) = explode(";base64,", $withoutSrc);
                //data:image/png
                list($part, $ext) = explode("/", $type);
                //Paste in temp file
                $withoutSrc = $tmpFolderPath."/".uniqid("temp_").".".$ext;
                @file_put_contents($withoutSrc, base64_decode($data));
            }

            //Set to array
            $arrSrc[] = $withoutSrc;
        }
    }
    return $arrSrc;
}
Share:
18,849
CarinaPilar
Author by

CarinaPilar

Software tester at work and programming as a hobby!

Updated on June 27, 2022

Comments

  • CarinaPilar
    CarinaPilar almost 2 years

    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/

  • CarinaPilar
    CarinaPilar over 10 years
    I tested, I wrote the content on a <P> tag and showed the right base64 content... It only doesn't "translate" as an image...
  • Renato Probst
    Renato Probst over 10 years
    Are you sure it showed all the data? How the size of the img? If it`s 1mb or more the post can cut part of the base64 down
  • Benjamin Vison
    Benjamin Vison about 7 years
    I am using a modified version of this, I go over the body of the template and I use the $message->embed from swiftmailer.org/docs/messages.html and I replace the content of src="X" with the cid of the file created by this function.. works like a charm! thanks!