I am using vanilla PHP to send emails with inline embedded images. Core of the code looks like this:
$from = "$from_name <$from_email>";
$reply = "$replyto_name <$replyto_email>";
$to = "$to_name <$to_email>";
$main_boundary = substr( sha1(rand()), 0, 20 );
$part_boundary = substr( sha1(rand()), 0, 20 );
$headers = "From: $from\n";
$headers .= "Reply-To: $reply\n";
$headers .= "X-Mailer: PHP script mailer\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= 'Content-Type: multipart/alternative;'."\n".' boundary="'.$main_boundary.'"'."\n";
$message=
'This is a multi-part message in MIME format.
--'.$main_boundary.'
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
'.$msgTXT.'
--'.$main_boundary.'
Content-Type: multipart/related;
boundary="'.$part_boundary.'"
--'.$part_boundary.'
Content-Type: text/html; UTF-8
Content-Transfer-Encoding: 7bit
'.$msgHTML.'
--'.$part_boundary.'
Content-Type: image/png; name="logo.png"
Content-Transfer-Encoding: base64
Content-Disposition: inline; filename="logo.png"
Content-ID: <part1.logo.111@example.com>
<base64 encoded image here>
--'.$part_boundary.'
Content-Type: image/gif; name="logo2.gif"
Content-Transfer-Encoding: base64
Content-Disposition: inline; filename="logo2.gif"
Content-ID: <part2.logo.222@example.com>
<base64 encoded image here>
--'.$part_boundary.'--
--'.$main_boundary.'--
';
$mailsent = mail ($to, $subject, $message, $headers);
What is important:
- declare Content-Type as multipart/alternative
- use 2 boundary blocks as markers/separators for email main boundary and part boundary for email components inside a main region. Note that it sends text and alternate HTML message. All inline images must be base64 encoded. Please note that \r\n\r\n is to be kept as it is for the code to work, it acts as separators as defined in RFC specifications. Same way one can use this mechanism to send emails with attachments just needs to select proper content-type.