I have a basic form consisting of input fields as well as a file field. I have a few things that I want the form to do. Collect the information (obviously). There's also an option to upload a file, (probably .doc,.pdf,.docx), so I want to restrict the attached file only to those extensions and under 2MB. All I know is that I have to have my form "enctype=multipart", but that's all I know.
I have the following PHP code:
<?
$to = 'my#email.com';
$subject = 'Contact from your website';
$message = 'From: ' . "\n\n" . 'Name: ' . $_REQUEST['name'] . "\n\n" . 'E-mail: ' . $_REQUEST['email'] . "\n\n" . 'Comments: ' . $_REQUEST['comments'];
$email = $_REQUEST['email'];
$headers = 'From: ' . $email . "\r\n" .
'Reply-To: ' . $email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$headers .= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/plain; charset=ISO-8859-1";
$str = $_REQUEST['email'];
if( $str == "E-mail address" || $str == "" )
{
echo "Please use your browser's back button enter a valid E-mail address";
} else {
mail ($to, $subject, $message, $headers);
header("Location: thankyou.html");
}
?>
How can I tweak it to allow it to send the attached file?
If possible, I'd love to see examples. Please understand that I'm extremely new to PHP, and until now have not needed to send PHP web forms with an attachment. So all that I ask of you is that if you post an example, please try to clarify the respective HTML form code that will work with the example.
Any help would be greatly appreciated!
Thanks a lot,
Amit
To mail an attachment, you can either use framework methods, or write the method yourself. Some sample code can be a good point to start.
To get a file sent from the browser, you have to use FILE variable. PHP documentation explains quite well how to do it.
To restrict file types to .doc and .pdf, you have to read the beginning of the file and compare to a "real" .doc or .pdf. An easier way would be to compare file extension, but the user of your website can always rename virus.exe to document.pdf.
haven't tested but it should work in theory.
Use this code which uses buffers.
(Code Source: http://www.webcheatsheet.com/PHP/send_email_text_html_attachment.php)
<?php
//define the receiver of the email
$to = 'youraddress#example.com';
//define the subject of the email
$subject = 'Test email with attachment';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster#example.com\r\nReply-To: webmaster#example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>--
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--
<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = #mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
Use PHPMailer. It's free, works well, and makes using attachments a snap. I've seen Swiftmailer mentioned a lot here on SO as well, but haven't used it myself so can't say much about it.
If you've access to the PEAR library, this'd make adding attachments a cinch. Have a look here.
Related
This question already has answers here:
Send attachments with PHP Mail()?
(16 answers)
Closed 4 years ago.
My form did send all info except of file/ How it is possible to fix it?
This is input file:
<input type="file" name="file" placeholder="ЗАГРУЗИТЬ ЧЕК" id="file_kd" required>
<br></p>
This is code php mail:
<?php
header('Refresh: 0; URL=http://yougotit.agency/kodabra/thank-you.php'); //
переадресация на страницу спасибо
$to = "stanislav.mandrik#gmail.com"; // емайл получателя данных из формы
$tema = "Kodabra - заявка успешно отправлена!"; // тема полученного емайла
$from = "Kodabra <no-reply#kodabra.com>";
$photo = $_FILES['file']['name'];
$message = "Ваше имя: ".$_POST['kdname']."<br>";
$message .= "E-mail: ".$_POST['kdemail']."<br>";
$message .= "Номер телефона: ".$_POST['kdphone']."<br>";
$message .= "Артикул модели (указан на упаковке): ".$_POST['kdartic']."<br>";
$message .= "Номер чека: ".$_POST['kdbill']."<br>";
$message .= "Комментарий: ".$_POST['kdcomment']."<br>";
$message .= "Согласился на обработку персональных данных. ".$_POST['kdagree']."<br>";
$message .= "Фото чека: ".($photo)."\n";
$headers = "MIME-Version: 1.0"."\r\n".
"Content-type: text/html; charset=\"utf-8\""."\r\n".
"From: $from"."\r\n";
mail($to, $tema, $message, $headers);
?>
from the answer that i marked duplicate please don't upvote this
To send an email with attachment we need to use the multipart/mixed MIME type that specifies that mixed types will be included in the email. Moreover, we want to use multipart/alternative MIME type to send both plain-text and HTML version of the email.Have a look at the example:
<?php
//define the receiver of the email
$to = 'youraddress#example.com';
//define the subject of the email
$subject = 'Test email with attachment';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster#example.com\r\nReply-To: webmaster#example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>--
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--
<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = #mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
As you can see, sending an email with attachment is easy to accomplish. In the preceding example we have multipart/mixed MIME type, and inside it we have multipart/alternative MIME type that specifies two versions of the email. To include an attachment to our message, we read the data from the specified file into a string, encode it with base64, split it in smaller chunks to make sure that it matches the MIME specifications and then include it as an attachment.
Taken from here.
In order to send email with file attachments you have to split the message into multiple parts with different encoding - here's how I do it. Note that there is a section for plain text information, and then it changes content encoding and adds any attachments by reading in the byte stream and re-encoding to base64 format and adding that to the message body, specifing content type, its file name, etc.
Of course, this all assumes that you have a working mail set up and a mail() of a plain text message works fine...
<?php
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From: $from_name <$from_address>\r\n";
$headers .= "Date: " . date("Ymd H:i:s") . "\r\n";
$headers .= "Reply-To: $from_name <$from_address>\r\n";
$headers .= "X-Priority: 1\r\n";
$headers .= "X-MSMail-Priority: High\r\n";
$headers .= "X-Mailer: ".$_SERVER['PHP_SELF']. "?id=". $_SERVER['UNIQUE_ID']. "\r\n";
$separator=md5(time());
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"\r\n";
$headers .= "Content-Transfer-Encoding: 7bit\r\n";
$headers .= "This is a MIME encoded message.\r\n";
// text message as normal for f2m
$messageBody="--".$separator."\r\n";
$messageBody.="Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
$messageBody.="Content-Transfer-Encoding: 8bit\r\n";
$messageBody.="\r\n".$message_body."\r\n\r\n";
// add attachments
// $attachments is basically the $_FILES array
for($i=0;$i<count($attachments);$i++){
$attachcontent=chunk_split(base64_encode(file_get_contents($attachments[$i]['tmp_name'])));
$messageBody.="--".$separator."\r\n";
$messageBody.="Content-Type: application/octet-stream; name=\"".$attachments[$i]['name']."\"\r\n";
$messageBody.="Content-Transfer-Encoding: base64\r\n";
$messageBody.="Content-Disposition: attachment; filename=\"".$attachments[$i]['name']."\"\r\n";
$messageBody.="\r\n".$attachcontent."\r\n";
}
$messageBody.="--" . $separator . "--";
mail($to_address, $subject, $messageBody, $headers);
?>
I have PHP code that sends email with attachment but what I want is to put all the data like Full Name, Contact Number, etc into a table. I tried using <table> but the email is still a plain text. Can someone help me how to make it?
This is my php code:
<?php
$cname = $_POST['Name'];
$cnumber = $_POST['Tel'];
$cemail = $_POST['emailadd'];
$cmess = $_POST['contactmess'];
$index = 'index.php';
move_uploaded_file($_FILES["attachment"]["tmp_name"] , "/files/upload/" . $_FILES["attachment"]["name"]);
$to = 'peace#gmail.com';
$subject = 'Careers Inquiry';
$random_hash = md5(date('r', time()));
$headers = "From: ". $cemail ."\r\nReply-To:". $cemail;
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
$headers .= "Content-Type: text/html; charset='iso-8859-1'";
$attachment = chunk_split(base64_encode(file_get_contents("/files/upload/" .$_FILES["attachment"]["name"])));
ob_start();
?>
--PHP-mixed-`<?php echo $random_hash; ?> `
Content-Type: multipart/alternative; boundary="PHP-alt-`<?php echo $random_hash; ?>`"
--PHP-alt-`<?php echo $random_hash; ?>`
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
--PHP-alt-`<?php echo $random_hash; ?>`
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<html>
<body>
<table>
<tr><td>Name: </td><td><?php echo $cname; ?></td></tr>
<tr><td>Contact Number: </td><td><?php echo $cnumber; ?></td></tr>
<tr><td>Email Address: </td><td><?php echo $cemail; ?></td></tr>
<tr><td>Message: </td><td><?php echo $cmess; ?></td></tr>
</table>
</body>
</html>
--PHP-alt-`<?php echo $random_hash; ?>`--
--PHP-mixed-`<?php echo $random_hash; ?>`
Content-Type: application/octet-stream; name="`<?php echo $_FILES["attachment"]["name"];?>`"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
`<?php echo $attachment; ?>`
--PHP-mixed-`<?php echo $random_hash; ?>`--
<?php
$message = ob_get_clean();
$mail_sent = #mail( $to, $subject, $message, $headers );
unlink('/files/upload/' . $_FILES["attachment"]["name"]);
echo $mail_sent ? header('Location: '. $index): '<script type="text/javascript"> alert("Sorry, service temporary unavailable."); </script>';
?>
For complex emailing with PHP checkout the PHPMailer class.
It is much easier to send complex emails (e.g. in HTML format) with the functions in PHPMailer.
It is easy to install and use. Look at the examples at the bottom of the linked page.
First up, if you can, pick up a library like:
Swiftmailer
PHPMailer
Pear's Mail_Mime
All the above have a bit of a learning curve to start, but the long run they will help you immensely. Getting mail headers and boundaries right so that spam filters don't pick up your mails is a real pain - and other people have solved these problems for you already.
However, if you insist on building the mail manually.
When constructing your headers it'll be easier to read if you split each one onto its own line and ensure that you end with a \r\n
E.g.
$headers = "From: $cemail\r\n";
$headers .= "Reply-To: $cemail\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"\r\n";
It looks like you might have missed a couple of \r\n off the last two headers.
Also, you duplicated your Content-Type headers. The second is not necessary as you specify the Content-Type on each boundary anyway.
charset should not be quoted.
I.E.
charset='iso-8859-1' and charset="iso-8859-1"
Should be
charset=iso-8859-1
It's possible those are your issues.
Running the output through Message Lint (http://www.apps.ietf.org/content/message-lint) doesn't throw up anything particular other than the above.
How do i send a mail in PHP with attachments?
I want to use pure php and not any libraries...
Here's what I already have tried:
<?php
//define the receiver of the email
$to = 'youraddress#example.com';
//define the subject of the email
$subject = 'Test email';
//define the message to be sent. Each line should be separated with \n
$message = "Hello World!\n\nThis is my first mail.";
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster#example.com\r\nReply-To: webmaster#example.com";
//send the email
$mail_sent = #mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
Try this:
<?php
//define the receiver of the email
$to = 'youraddress#example.com';
//define the subject of the email
$subject = 'Test email with attachment';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster#example.com\r\nReply-To: webmaster#example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>--
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--
<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = #mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
Reference: http://webcheatsheet.com/PHP/send_email_text_html_attachment.php
You can try the following, but first you will need to make changes to these:
$name = 'image.jpg';
// The path to the image with the file name:
$fileatt = "images/".$name;
Which is within the code below: (pre-tested)
<?php
// Set who this goes to:
$to = array('Your Name','email#example.com');
// Give the message a subject:
$subject = 'Some subject';
// Set who this message is from:
$from = array("My Company", "email#example.com");
// Create the header information:
$random_hash = md5(date('r', time()));
$mime_boundary = "==Multipart_Boundary_x{$random_hash}x";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-Type: multipart/mixed; boundary="'.$mime_boundary.'"' . "\r\n";
$headers .= 'To: '.$to[0].' <'.$to[1].'>' . "\r\n";
$headers .= 'From: '.$from[0].' <'.$from[1].'>' . "\r\n";
// Build the message (can have HTML in it) message:
$message = 'This is an <b>HTML message</b> it comes with an attachment!'."\n\n".
// Do not edit this part of the message:
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
// The image that you would like to send (filename only):
$name = 'image.jpg';
// The path to the image with the file name:
$fileatt = "images/".$name;
$fileatt_type = "application/octet-stream"; // File Type
// Filename that will be used for the file as the attachment
$fileatt_name = $name;
// Read the file attachment:
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
// Create sendable information
$data = chunk_split(base64_encode($data));
// Finalize the message with attachment
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}\n";
unset($data);
unset($file);
unset($fileatt);
unset($fileatt_type);
unset($fileatt_name);
// Send the message:
mail($to[1], $subject, $message, $headers);
echo "Email sent";
?>
You need to make use of base64 encoding inorder to attach a file. So here goes a simpler code.
<?php
$to = "someone#somewhere.com";
$subject = "Email with an Attachment with no Special libraries";
$random_hash = md5(date('r', time()));
$headers = "From: someid#yoursite.com\r\nReply-To: noreply#so.com";
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
$attachment = chunk_split(base64_encode(file_get_contents("pics.zip")));
$output = "somecontent";
echo mail($to, $subject, $output, $headers);
?>
here's (all) the code:
<?php
/*
WHITE SPACE MATTERS IN THIS DOCUMENT
*/
include("_php/ChromePhp.php");
// define receiver of email
$to = "person#place.com";
// define subject of email
$subject = "<--== KABAM! HTML Email from WR! ==-->";
// define message to send. use /n for linebreaks
//$message = 'This is the message. Read it. Love it.';
// create a boundary string. it must be unique!
$uniqID = md5(date('r', time()));
// define the headers. separated by \r\n
$headers = "From: some dude" . "\r\n";
$headers .= "Reply-To: nobody" . "\r\n";
$headers .= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"PHP-mixed-".$uniqID."\""."\r\n";
// read the attachment into a string, encode it and then
// split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('./_dox/pdftmp/emailTESTER.zip')));
// define the body of the message
ob_start(); // turn on output buffering
?>
--PHP-mixed-<?php print $uniqID; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php print $uniqID; ?>
--PHP-alt-<?php print $uniqID; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
This is the TEXT email.
Nothing but pure text. not really fun...
--PHP-alt-<?php print $uniqID; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h1>This is the HTML test email.</h1>
<h3>Read it. Love it.</h3>
<p>this is all HTML. without any CSS, mind you...</p>
<?php include("_php/formEmail.php"); ?>
--PHP-alt-<?php print $uniqID; ?>--
--PHP-mixed-<?php print $uniqID; ?>
Content-Type: application/zip; name="emailTESTER.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php print $attachment; ?>
--PHP-mixed-<?php print $uniqID; ?>--
<?php
// copy current buffer contents into $message then delete
// the contents of the output buffer
$message = ob_get_clean();
// send the email
$mail_sent = #mail($to, $subject, $message, $headers);
// display a message depending on mail_sent status
print $mail_sent ? "Mail Sent: ".$uniqID : "Mail Failed: ".$uniqID;
?>
and this is what pops out in the email client: (doesn't render...)
This is the TEXT email.
Nothing but pure text. not really fun...
--PHP-alt-a0d18dbf6c6ec8fb30c47adc84234c75Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h1>This is the HTML test email.</h1>
<h3>Read it. Love it.</h3>
<p>this is all HTML. without any CSS, mind you...</p>
--PHP-alt-a0d18dbf6c6ec8fb30c47adc84234c75--
the attachment, instead of being "emailTESTER.zip" is simply "Part 2" and no extension. if i add '.zip', it becomes the correct archive (albeit misnamed) with the correct contents...
i triple checked the boundary lines, i believe they are correctly set. the only thing that i could think of would be something in the Content-Type declarations...but if it is, i'm blank as to what it might be... i've read all the prior posts on "PHP email HTML blah blah" and while they lent insight, none of them touched on my odd pair of hiccups. narf
so. what did i miss? why is it not working correctly/completely?
TIA.
WR!
Don't reinvent the wheel. Use an existing mail class. PHPMailer is excellent.
The code below is sending an email correctly but for the body. I need to show html in the body of the message and I cannot make it. The examples in the web won't send the email :(
How can I fix my code to send the email with the html in the body?
Thanks a ton!
<?php
$to = 'mymail#mail.com';
$subject = 'I need to show html';
$from ='example#example.com';
$body = '<p style=color:red;>This text should be red</p>';
ini_set("sendmail_from", $from);
$headers = "From: " . $from . "\r\nReply-To: " . $from . "";
$headers .= "Content-type: text/html\r\n";
if (mail($to, $subject, $body, $headers)) {
echo("<p>Sent</p>");
} else {
echo("<p>Error...</p>");
}
?>
use this header for the mail:
$header = "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html; charset: utf8\r\n";
and for the content/body:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
... ... ...
it's important to use inline css commands and recommanded to use tables for the interface.
...
In your Mail-Body you than have to put HTML code with head and body
Have you looked at the headers of the incoming mail? It says
Reply-To: example#example.comContent-type: text/html
Simply add another \r\n here:
Reply-To: " . $from . "\r\n";
I recommend rather than messing around with doing this yourself you use one of the many free classes available all over the web to do it.
I would recommend: PHPMailer
I found this works well!
Source
<?php
//define the receiver of the email
$to = 'youraddress#example.com';
//define the subject of the email
$subject = 'Test HTML email';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster#example.com\r\nReply-To: webmaster#example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/alternative; boundary=\"PHP-alt-".$random_hash."\"";
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>--
<?
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = #mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
Simple answer: Don't do it. HTML emails are evil and annoying. At least if there's no PROPER plaintext version included. Proper = same information like in the HTML version, not just a stupid comment about getting another email client or a link to the html version if it's available on the web.
If you really need it: http://pear.php.net/package/Mail_Mime