Search code examples
phpimagegoogle-maps-api-3phpmailer

Embed Image in Mail without having physical Image File


I´m using Google Maps Static API to request an Image as PNG. Currently I´m saving this Image to the Filesystem and afterwards I´m sending this Image with PHPMailer to my clients. After all Mails are send, the Image is removed from the Filesystem.

My intention is now to save me the step of saving the Image to the Filesystem and just use the Image Object from Memory and send it via Mail. But it seems that PHPMailer must have an Image on the Filesystem to use it.

What I currently do:

Request Image from Static API

 $URL = "http://maps.googleapis.com/maps/api/staticmap?center=Albany,+NY&zoom=13&scale=false&size=600x300&maptype=roadmap&format=png&visual_refresh=true";
 $image = file_get_contents($URL);

Save Image to Filesystem and send it to my Mail Function

 $fp  = fopen('../../img/staticMap/staticMap.png', 'w+');

 fputs($fp, $image);
 fclose($fp);
 unset($image);

 $file = "../../img/staticMap/staticMap.png";
 $notifications->notifySingleUser($file); //Call my Mail Function

Embed Image in Mail

$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->IsHTML(true);
$mail->AddEmbeddedImage($file, "staticMap");
$mail->Body = "<img width="600" height="300" src="cid:staticMap">";

I´ve also done some research PHPMailer attachment, doing it without a physical file, but here they are just talking how to do it with AddAttachment, but I want to AddEmbeddedImage. I´ve also tried that, the Mail is send without any error´s, but with NO image in it.

Is this even possible? If yes, how could I archive it?


Solution

  • It always helps to read the docs. The function you're looking for is addStringEmbeddedImage, which does exactly what you want:

    $URL = "http://maps.googleapis.com/maps/api/staticmap?center=Albany,+NY&zoom=13&scale=false&size=600x300&maptype=roadmap&format=png&visual_refresh=true";
    $image = file_get_contents($URL);
    $mail->addStringEmbeddedImage($image, 'staticMap', 'map.png', 'base64', 'image/png');
    $mail->Body = '<img width="600" height="300" src="cid:staticMap">';
    

    There are indeed pros and cons to using embedded images, but data urls have especially poor client compatibility, so are generally the worst option. Dynamically linking to the image may not be reliable with google maps, so you may want to proxy and cache the direct map lookups. This will also be much faster than hitting the API every time, and also more reliable as you can deliver an older version if the API doesn't respond or is slow.