how to send an HTML email with an inline attached image with PHP

江枫思渺然 提交于 2019-11-27 09:19:57

I finally found the answer, which turns out to be remarkably simple. This page is what helped me figure it out, but I'll demonstrate the parts that I needed to get it done below.

First off, there's the creation of the boundary string, and the image, correctly encoded and chunked:

// Create a boundary string.  It needs to be unique (not in the text) so ...
// We are going to use the sha1 algorithm to generate a 40 character string:
$sep = sha1(date('r', time()));

// Also now prepare our inline image - Also read, encode, split:
$inline = chunk_split(base64_encode(file_get_contents('figure.gif')));

In the HTML part of the email, the image is referenced like this (using the boundary string):

<img src="cid:PHP-CID-{$sep}">

Then you create another part of the email below the HTML part for the inline attachment, like this:

--PHP-related-{$sep}
Content-Type: image/gif
Content-Transfer-Encoding: base64
Content-ID: <PHP-CID-{$sep}>
{$inline}

...and that is that! Easier than implementing PHPmailer or any of the other libraries, if this is all you're doing. No doubt for more complicated task, you'll want to get one of those libraries.

Charles Forest

I would recommend using PHPMailer but since you say you don't want to I suggest this quick fix.

Put the absolute URL inside an img tag, if you do send an HTML email, it will work.

<img src="http://example.com/image.jpg"/>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!