Subscribe

RSS Feed (xml)

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:

01<?php
02 // Setting a timezone, mail() uses this.
03 date_default_timezone_set('America/New_York');
04  // recipients
05 $to  = "you@miscellaneous4all.blogspot.com" . ", " ; // note the comma
06 $to .= "we@miscellaneous4all.blogspot.com";
07 
08  // subject
09 $subject = "Test for Embedded Image & Attachement";
10 
11 // Create a boundary string.  It needs to be unique
12 $sep = sha1(date('r', time()));
13 
14 // Add in our content boundary, and mime type specification: 
15 $headers .=
16    "\r\nContent-Type: multipart/mixed;
17     boundary=\"PHP-mixed-{$sep}\"";
18 
19 // Read in our file attachment
20 $attachment = file_get_contents('attachment.zip');
21 $encoded = base64_encode($attachment);
22 $attached = chunk_split($encoded);
23 
24 // additional headers
25 $headers .= "To: You <you@miscellaneous4all.blogspot.com>,
26             We <we@miscellaneous4all.blogspot.com>\r\n";
27 $headers .= "From: Me <me@miscellaneous4all.blogspot.com>\r\n";
28 $headers .= "Cc: he@miscellaneous4all.blogspot.com\r\n";
29 $headers .= "Bcc: she@miscellaneous4all.blogspot.com\r\n";
30 
31 $inline = chunk_split(base64_encode(
32           file_get_contents('mypicture.gif')));
33 
34 // Your message here:
35 $body =<<<EOBODY
36 --PHP-mixed-{$sep}
37 Content-Type: multipart/alternative;
38               boundary="PHP-alt-{$sep}"
39 
40 --PHP-alt-{$sep}
41 Content-Type: text/plain
42 
43 Hai, It's me!
44 
45 
46 --PHP-alt-{$sep}
47 Content-Type: multipart/related; boundary="PHP-related-{$sep}"
48 
49 --PHP-alt-{$sep}
50 Content-Type: text/html
51 
52 <html>
53 <head>
54 <title>Test HTML Mail</title>
55 </head>
56 <body>
57 <font color='red'>Hai, it is me!</font>
58 Here is my picture:
59  <img src="cid:PHP-CID-{$sep}" />
60 </body>
61 </html>
62  
63 --PHP-related-{$sep}
64 Content-Type: image/gif
65 Content-Transfer-Encoding: base64
66 Content-ID: <PHP-CID-{$sep}>
67  
68 {$inline}
69 --PHP-related-{$sep}--
70  
71 --PHP-alt-{$sep}--
72 
73 --PHP-mixed-{$sep}
74 Content-Type: application/zip; name="attachment.zip"
75 Content-Transfer-Encoding: base64
76 Content-Disposition: attachment
77 
78 {$attached}
79 
80 --PHP-mixed-{$sep}--
81 EOBODY;
82  
83 // Finally, send the email
84 mail($to, $subject, $body, $headers);
85 ?>
86</me@miscellaneous4all.blogspot.com>

0 comments:

Related Posts with Thumbnails