PHPMailer, AddStringAttachment and Data URI Scheme

Samuel Cotterall picture Samuel Cotterall · Jul 29, 2009 · Viewed 16.2k times · Source

I have converted the contents of a canvas element to data (URI Scheme) using toDataURL() ($contact_image_data) and I want to send this via email as an attachment. This is currently how I have PHPMailer set up:

$contact_image_data="data:image/png;base64,iVBORw0KGgo[...]";
$filename="test.png"; 
$encoding = "base64"; 
$type = "image/png";
$mail->AddStringAttachment($contact_image_data, $filename, $encoding, $type);   

I am wondering if this is actually possible, and if so, what steps I am missing.

I can send an email, attach a file named “test.png” which contains the contents of $contact_image_data, but it doesn’t actually create an image.

Any help would be much appreciated.

Samuel.

Answer

Samuel Cotterall picture Samuel Cotterall · Jul 29, 2009

It turns out I needed to strip the data:image/png;base64, section and base64_decode() the data:

$contact_image_data="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA";
$data = substr($contact_image_data, strpos($contact_image_data, ","));
$filename="test.png"; 
$encoding = "base64"; 
$type = "image/png";
$mail->AddStringAttachment(base64_decode($data), $filename, $encoding, $type);