PHP Email: Using Embedded Images in HTML Email


PHP Email Tutorial: We ever talk how about send email with attachment. Now, in this post, we want to send email where there is images in there as embedded images. Usually, you get this kind of email from newsletter. So, after read this post, you can build your own newsletter.

Before we write line codes, we must understand following anatomy of email that use embedded images:

anatomy of email that use embedded image

After it, It is easy for us to understand this code:

 <?php
 // Setting a timezone, mail() uses this.
 date_default_timezone_set('America/New_York');
  // recipients
 $to  = "you@phpeveryday.com" . ", " ; // note the comma 
 $to .= "we@phpeveryday.com"; 

  // subject 
 $subject = "Test for Embedded Image & Attachement"; 

 // Create a boundary string.  It needs to be unique 
 $sep = sha1(date('r', time()));

 // Add in our content boundary, and mime type specification:  
 $headers .=
    "\r\nContent-Type: multipart/mixed; 
     boundary=\"PHP-mixed-{$sep}\"";

 // Read in our file attachment
 $attachment = file_get_contents('attachment.zip');
 $encoded = base64_encode($attachment);
 $attached = chunk_split($encoded);

 // additional headers
 $headers .= "To: You <you@phpeveryday.com>, 
             We <we@phpeveryday.com>\r\n"; 
 $headers .= "From: Me \r\n"; 
 $headers .= "Cc: he@phpeveryday.com\r\n"; 
 $headers .= "Bcc: she@phpeveryday.com\r\n";

 $inline = chunk_split(base64_encode(
           file_get_contents('mypicture.gif')));

 // Your message here:
 $body =<<<EOBODY
 --PHP-mixed-{$sep}
 Content-Type: multipart/alternative; 
               boundary="PHP-alt-{$sep}"

 --PHP-alt-{$sep}
 Content-Type: text/plain

 Hai, It's me!


 --PHP-alt-{$sep}
 Content-Type: multipart/related; boundary="PHP-related-{$sep}"

 --PHP-alt-{$sep}
 Content-Type: text/html

 <html>
 <head>
 <title>Test HTML Mail</title>
 </head>
 <body>
 <font color='red'>Hai, it is me!</font>
 Here is my picture: 
  <img src="cid:PHP-CID-{$sep}" />
 </body>
 </html>
 
 --PHP-related-{$sep}
 Content-Type: image/gif
 Content-Transfer-Encoding: base64
 Content-ID: <PHP-CID-{$sep}> 
 
 {$inline}
 --PHP-related-{$sep}--
 
 --PHP-alt-{$sep}--

 --PHP-mixed-{$sep}
 Content-Type: application/zip; name="attachment.zip"
 Content-Transfer-Encoding: base64
 Content-Disposition: attachment

 {$attached}

 --PHP-mixed-{$sep}--
 EOBODY;
 
 // Finally, send the email
 mail($to, $subject, $body, $headers);
 ?>


Series this article:
Email: Sending a Simple Email (Part 1)
Email: Sending a Simple HTML Mail (Part 2)
Email: Sending Dual Format (Part 3)
Email: Send Attachement Mail
PHP Email: Using Embedded Images in HTML Email
PHP Email: Sending Mass Email use BCC
PHP Email: Protecting Email Address from Spam Collectors

Bookmark and Share Tag: email, images Category: PHP Basic Post : January 02nd 2008 Read: 173,719

advertisements


blog comments powered by Disqus