Sending HTML-email with Attachment Using PHP’s mail() Function November 18, 2011
Posted by Tournas Dimitrios in PHP.trackback
Sending email with PHP is a basic functionality , in most cases your installation of PHP will be capable of sending emails out-of-the-box . If you are using a shared host , or if you installed PHP using a package management system like YUM (Red-Hat) more than likely you’re all set . You’ll really only need to worry about extra configuration if you’re compiling PHP from source or if you’re running it on Windows . PHP’s native mail functionality is achieved through its mail() function . An absolute basic example could be :
php // The message $message = "Your long message goes here "; /* In case any of our lines are larger than 70 characters, we should use wordwrap() */ $message = wordwrap($message, 70); // Send mail('caffeinated@example.com', 'My Subject', $message); ?>
The mail function accepts 5 parameters (the last 2 are optional ie header and options) :
- 4th –header : Structured into fields such as From , To , CC , Subject , Date , and other information about the email (MIME-type) . Remember to always end each header line with a \r\n and always use double quotes , if you use single quotes the \r\n will be ignored . Originally email was designed to transfer only plain text , though as Internet made huge evolution , other content types were transferred like : html , pictures , digital file-formats …. By adding the MIME type into the header we basically saying to the email client (and the MTA ) that the content is something other than a plain text email (although plain text can still be sent with the MIME type set) . The MIME type has a long list of identifiers that define what content type will be included into the email .
- The 5th is optional for sendmail configuration
To send an HTML email , the process is the same, however , you need to provide additional headers (MIME) , as well as an HTML formatted message .
<?php // Set up parameters $to = "user1@example.com"; $subject = "Your password"; $from = "admin@itservice.com"; $message = "</pre> <h3>Hello User1 ,</h3> <pre> <p>Thanks for registering .</p> <p>Your password is : <span style='color:red'><b>User@1$#!</b></span></p> "; $headers = "MIME-Version: 1.0" . "\n"; $headers .= "Content-type:text/html;charset=iso-8859-1" . "\n"; $headers .= "From: $from" . "\n"; // Send email $success = mail($to,$subject,$message,$headers); if (!$success) { echo "Mail to " . $to . " failed ."; }else { echo "Success : Mail was send to " . $to ; } ?>
In MIME type emails you basically can put as many things as you like in your email as long as they are separated by a boundary (custom string ) . Consider the scenario where you send an email for email-clients that doesn’t support html content but the same email will be used by email-clients that has html support and inline picture display and attachments . If you stack those content all together in an email how will the email-client know when to stop displaying one and display another ? The answer is , the boundary string .
<?PHP $to = "user1432@gmail.com"; $subject = "Your password with attachment test"; $from = "admin@itservice.com"; $headers = "From: $from\r\n"; $headers .= "MIME-Version: 1.0\r\n" ."Content-Type: multipart/mixed; boundary=\"1a2a3a\""; $message .= "If you can see this MIME than your client doesn't accept MIME types!\r\n" ."--1a2a3a\r\n"; $message .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n" ."Content-Transfer-Encoding: 7bit\r\n\r\n" ."hey my <b>good</b> friend here is a picture of me" ."<p>Your password is : <span style='color:red'><b>User@1$#!</b></span></p> \r\n" ."--1a2a3a\r\n"; $file = file_get_contents("picture.jpg"); $message .= "Content-Type: image/jpg; name=\"picture.jpg\"\r\n" ."Content-Transfer-Encoding: base64\r\n" ."Content-disposition: attachment; file=\"picture.jpg\"\r\n" ."\r\n" .chunk_split(base64_encode($file)) ."--1a2a3a--"; // Send email $success = mail($to,$subject,$message,$headers); if (!$success) { echo "Mail to " . $to . " failed ."; }else { echo "Success : Mail was send to " . $to ; } ?>
The picture below demonstrates how the email will displayed through my web- mail ( browser ) .
Let’s recap : Email headers contain the : Cc , BCc , From , To and the MIME information . MIME defines the version of itself (1.0 is the current standard version ) , content-type , transfer-encoding and boundary string . A full list of MIME content-types can be found on Wikipedia . Emails constructed with the multipart type MIME allows messages to have multipart content arranged in a tree structure where the leaf nodes are any non-multipart content type and the non-leaf nodes are any of a variety of multipart types . Most commonly, multipart/alternative is used for email with two parts , one plain text (text/plain) and one HTML (text/html) . The plain text part provides backwards compatibility while the HTML part allows use of formatting and hyperlinks . Most email clients offer a user option to prefer plain text over HTML . Confused by this last paragraph ? Let the code explain this subject .
<?PHP $to = "user1476@gmail.com"; $subject = "Your password with attachment test"; $from = "admin@itservice.com"; $myAttachment = chunk_split(base64_encode(file_get_contents( "logreport.rar"))); $headers = "From: \"Webmaster\" <admin@itsupport.com>\r\n" . "Repy-To: admin@itsupport.com\r\n" . "MIME-Version: 1.0\r\n" . "Content-Type: multipart/mixed; boundary= \"1a2a3a\"\r\n"; $body = "--1a2a3a\r\n" . "Content-Type: multipart/alternative; boundary= \"4a5a6a\"\r\n" . "--4a5a6a\r\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n" . "Content-Transfer-Encoding: 7bit\r\n" . "The attachment contains the log-files .\r\n" . "--4a5a6a\r\n" . "Content-Type: text/html; charset=\"iso-8859-1\"\r\n" . "<html> <head> <title>Report of last months log files</title> </head> <body></pre> <span style="color: red;"><strong>Please keep in mind :</strong></span> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. <pre> </body> </html>\r\n" . "--1a2a3a\r\n" . "Content-Type: application/zip; name=\"logreport.rar\"\r\n" . "Content-Transfer-Encoding: base64\r\n" . "Content-Disposition: attachment\r\n" . $myAttachment. "\r\n" . "--1a2a3a--"; $success = mail($to, $subject, $body, $headers); if (!$success) { echo "Mail to " . $to . " is fail."; }else { echo "Success : Mail was send to " . $to ; } ?>
Final notes :
This article was just an introduction of how we can manipulate email headers and send all kind of content into email-messages . PHP provides alternative solutions (wrapper classes) to make our job more pleasant . My previous article demonstrated how the phpMailer class sends attachments with just a few lines of code . PhpMailer can do much more in a simpler way . Future articles will show Zend Framework’s mail module and PHP’s Swing class , so stay tuned …..
[…] previous article ” Sending HTML-email with Attachment Using PHP’s mail() Function ” has shown that it’s possible to configure the headers of an email-message for […]
Thanks for this. I search hi and low on how to send email with attachment with HTML message but none of the examples worked except this one.
@Pritesh Patei
My intention was to demonstrate the basic structure of an email-package .My example use “hard-coded” content . In a production environment you would use data submitted by users to send mail . Be very careful when implementing this code on an production environment , you should sanitize the content submitted by users to prevent “email header injection” . In simple words : somebody could send spam mail through your website or send rude messages and impersonate that it was send by you .
[…] Sending HTML-email with Attachment Using PHP’s mail() Function […]
it’s great i got attachment..