PHP Attaching an image to an email

Try the PEAR Mail_Mime package, which can embed images for you.

You need to use the addHTMLImage() method and pass a content id (cid), which is a unique string of text you will also use in your img’s src attribute as a cid: URL. For example:

include('Mail.php');
include "Mail/mime.php";


$crlf = "\r\n";
$hdrs = array( 
        'From' => '[email protected]', 
        'Subject' => 'Mail_mime test message' 
        ); 

$mime = new Mail_mime($crlf); 

//attach our image with a unique content id
$cid="mycidstring";
$mime->addHTMLImage("/path/to/myimage.gif", "image/gif", "", true, $cid);

//now we can use the content id in our message
$html="<html><body><img src="https://stackoverflow.com/questions/536838/cid:".$cid.'"></body></html>';
$text="Plain text version of email";

$mime->setTXTBody($text);
$mime->setHTMLBody($html); 

$body = $mime->get();
$hdrs = $mime->headers($hdrs);

$mail =& Mail::factory('mail');
$mail->send('[email protected]', $hdrs, $body);

Leave a Comment