How to Attach an Image to an Email Using PHP

I recently wrote a small data acquisition system using PHP. I’m not a fan of web-based development and know very little but I had some financial incentive for this project and took it upon myself to learn along the way. By far the biggest headache I ran into was dealing with PHP’s mail() function. There’s obviously a reason so many third party libraries exist that tackle this issue but, being stubborn, I wanted to do it from scratch.

My goal was to generate and send an email consisting of an HTML body with an image attached. Embedding the image within the HTML turned out to be fairly trivial (in comparison) but an attachment was preferred. After MUCH ado I came up with the following function which does just that.

NOTE: This function doesn’t go to any extremes to validate itself and doesn’t make it past very many junk filters. This was fine for my use case as the email will be going to a single administrator who can easily whitelist the domain. However, if this is a concern I would highly recommend using one of the third party libraries as considerable configuration is required both in the PHP and on the delivering server itself.

# Send mail with an attachment
function mailAttachment($to, $subject, $body, $from, $photoPath, $photoName, $filetype)
	$bound_text = md5(uniqid(rand(), true));;
	$bound = "--" . $bound_text . "\r\n";
	$bound_last = "--" . $bound_text . "--\r\n";

	$headers = "From:" . $from . "\r\n"
	. "MIME-Version: 1.0\r\n"
	. "Content-Type: multipart/mixed; boundary=\"$bound_text\"";

	$message =	"Sorry, your client doesn't support MIME types.\r\n"
	. $bound;

	$message .=	"Content-Type: text/html; charset=\"iso-8859-1\"\r\n"
	. "Content-Transfer-Encoding: 7bit\r\n\r\n"
	. $body
	. $bound;

	$file =	file_get_contents($photoPath);

	$message .=	"Content-Type: $filetype; name=\"$photoName\"\r\n"
	. "Content-Transfer-Encoding: base64\r\n"
	. "Content-disposition: attachment; file=\"$photoName\"\r\n"
	. "\r\n"
	. chunk_split(base64_encode($file))
	. $bound_last;

	if(mail($to, $subject, $message, $headers)) 
	     echo 'MAIL SENT!' . '<br>';
	     echo 'to: ' . $to . '<br>';
	     echo 'from: ' . $from . '<br>';
	     echo 'bodyText: ' . $body . '<br>';
	     echo 'photoPath: ' . $photoPath . '<br>';
	     echo 'photoName: ' . $photoName . '<br>';
	     echo 'filetype: ' . $filetype . '<br>';
	     echo 'MAIL FAILED';

mailAttachment('', 'attachmentTest', 'SomeHTML', '', 'uploads/testImage.png', 'testImage.png', 'image/png');

Leave a Reply

Your email address will not be published. Required fields are marked *