After learn send email with dual format (HTML/text), we will learn how to send email with attachment. In this situation, we will make the primary MIME type be multipart/mixed so that we can do an attachment or two.
01 | <?php |
02 | // Setting a timezone, mail() uses this. |
03 | date_default_timezone_set('America/New_York'); |
04 | // recipients |
05 | $to = "you@miscellaneous4all.com" . ", " ; // note the comma |
06 | $to .= "we@miscellaneous4all.com"; |
07 |
08 | // subject |
09 | $subject = "Test for 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, |
15 | // and mime type specification: |
16 | $headers .= |
17 | "\r\nContent-Type: multipart/alternative; |
18 | boundary=\"PHP-alt-{$sep}\""; |
19 |
20 | // Read in our file attachment |
21 | $attachment = file_get_contents('attachment.zip'); |
22 | $encoded = base64_encode($attachment); |
23 | $attached = chunk_split($encoded); |
24 |
25 | // additional headers |
26 | $headers .= "To: You <you@miscellaneous4all.com>, |
27 | We <we@miscellaneous4all.com>\r\n"; |
28 | $headers .= "From: Me <me@miscellaneous4all.com>\r\n"; |
29 | $headers .= "Cc: he@miscellaneous4all.com\r\n"; |
30 | $headers .= "Bcc: she@miscellaneous4all.com\r\n"; |
31 |
32 | // Your message here: |
33 | $body =<<<EOBODY |
34 | --PHP-alt-{$sep} |
35 | Content-Type: text/plain |
36 |
37 | Hai, It's me! |
38 |
39 | --PHP-alt-{$sep} |
40 | Content-Type: text/html |
41 |
42 | <html> |
43 | <head> |
44 | <title>Test HTML Mail</title> |
45 | </head> |
46 | <body> |
47 | <font color='red'>Hai, it is me!</font> |
48 | </body> |
49 | </html> |
50 |
51 | --PHP-alt-{$sep}-- |
52 |
53 | --PHP-mixed-{$sep} |
54 | Content-Type: application/zip; name="attachment.zip" |
55 | Content-Transfer-Encoding: base64 |
56 | Content-Disposition: attachment |
57 |
58 | {$attached} |
59 |
60 | --PHP-mixed-{$sep}-- |
61 | EOBODY; |
62 |
63 | // Finally, send the email |
64 | mail($to, $subject, $body, $headers); |
65 | ?> |
66 | </me@miscellaneous4all.com> |