People will chime in to tell you to use SwiftMailer or some other library. But it's not that hard. It's really finicky, but not hard. Below is a function I use. I've anonymized it a bit, and hopefully didn't break anything. In the html message (which I get from another function), link to your attached image this way:
$output .= '<p><img src="cid:' . $linkID . '" alt="graph" /></p>';
Where $linkID
is the same value used in the function below.
public function sendEmail($emailAddress)
{
$random_hash = md5(date('r', time()));
$htmlString = $this->getHTML($random_hash);
$message = "--mixed-$random_hash\n";
$message .= 'Content-Type: multipart/alternative; boundary="alt-' . $random_hash . '"' . "\n\n";
$message .= 'MIME-Version: 1.0' . "\n";
$message .= '--alt-' . $random_hash . "\n";
$message .= 'Content-Type: text/plain; charset="iso-8859-1"' . "\n";
$message .= 'Content-Transfer-Encoding: 7bit' . "\n\n";
// text message
$message .= strip_tags($htmlString) . "\n\n";
$message .= '--alt-' . $random_hash . "\n";
$message .= 'Content-Type: text/html; charset="iso-8859-1"' . "\n";
// $message .= 'MIME-Version: 1.0' . "\n";
$message .= 'Content-Transfer-Encoding: 7bit' . "\n\n";
// html message
$message .= $htmlString . "\n\n";
$message .= '--alt-' . $random_hash . '--' . "\n";
// graph image
if($this->selectedGraph != 0)
{
$graphString = $this->getGraph();
$graphString = chunk_split(base64_encode($graphString));
$linkID = 'graph-' . $random_hash . '-image';
$message .= '--mixed-' . $random_hash . "\n";
$message .= 'MIME-Version: 1.0' . "\n";
$message .= 'Content-Transfer-Encoding: base64' . "\n";
$message .= 'Content-ID: ' . $linkID . "\n";
$message .= 'Content-Type: image/gif; name="graph.gif"' . "\n";
$message .= 'Content-Disposition: attachment' . "\n\n";
$message .= $graphString;
$message .= '--mixed-' . $random_hash . '--' . "\n";
}
else
{
$message .= '--mixed-' . $random_hash . '--' . "\n";
}
$headers = 'From: ' . $this->from. "\r\nReply-To: " . $this->replyto;
$headers .= "\r\nContent-Type: multipart/related; boundary=\"mixed-" . $random_hash . "\"\r\nMIME-Version: 1.0";
$flags = '-f ' . BOUNCED_EMAIL_ADDRESS;
return mail($emailAddress, $this->subject, $message, $headers, $flags);
}
Whether or not it's worthwhile to do is another question. If you attach the image, you're using bandwidth to send the message out. Maybe it's better for you to use the bandwidth all at once rather than spread out? Maybe not.
I didn't use attached images until I had to send out a different image to each recipient. I wasn't about to store and manage all of those images on our server (and try to uniquely name them).