View Full Version : integrating two example scripts to email attachment help please

01-19-2004, 06:49 AM
Hello, from what I've been researching on PHP.net, not to mention many other sources, I've found two examples of code that will allow me to sent an html email with attachments using mail(). However, the examples are not integrated and I'm wondering if someone could help out with this? This may indeed be very valuable to many beginning php'ers like me.

Here are the two examples of code from PHP.net I would like to use to email:

1) to send the html email
/* recipients */
$to = "mary@example.com" . ", " ; // note the comma
$to .= "kelly@example.com";

/* subject */
$subject = "Birthday Reminders for August";

/* message */
$message = '
<title>Birthday Reminders for August</title>
<p>Here are the birthdays upcoming in August!</p>

/* To send HTML mail, you can set the Content-type header. */
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";

/* additional headers */
$headers .= "To: Mary <mary@example.com>, Kelly <kelly@example.com>\r\n";
$headers .= "From: Birthday Reminder <birthday@example.com>\r\n";

/* and now mail it */
mail($to, $subject, $message, $headers);
2) to add the attachments
To add an attachment to a mail:

function mail_attach($to, $from, $subject, $message, $file) {
// $to Recipient
// $from Sender (like "email@domain.com" or "Name <email@domain.com>")
// $subject Subject
// $message Content
// $file File (on server) to attach
$mime_boundary = "<<<:" . md5(uniqid(mt_rand(), 1));
$data = chunk_split(base64_encode(implode("", file($file))));
$header = "From: ".$from."\r\n";
$header.= "To: ".$to."\r\n";
$header.= "MIME-Version: 1.0\r\n";
$header.= "Content-Type: multipart/mixed;\r\n";
$header.= " boundary=\"".$mime_boundary."\"\r\n";

$content = "This is a multi-part message in MIME format.\r\n\r\n";
$content.= "--".$mime_boundary."\r\n";
$content.= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
$content.= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$content.= $message."\r\n";
$content.= "--".$mime_boundary."\r\n";
$content.= "Content-Disposition: attachment;\r\n";
$content.= "Content-Type: Application/Octet-Stream; name=\"".$file."\"\r\n";
$content.= "Content-Transfer-Encoding: base64\r\n\r\n";
$content.= $data."\r\n";
$content.= "--" . $mime_boundary . "\r\n";
if(mail($to, $subject, $content, $header)) {
return TRUE;
return FALSE;
mail_attach($to, "Sender <sender@address.com>", "Subject", $text, "./mydir/file.jpg");

I'm also wondering about the actual mail_attach() function as the file name is actually the path to the file. Can this be a variable instead in order to validate the file?

Thank you to anyone interested in helping out with this...