Wednesday, February 17, 2010

PHP - Send email with attachment | Email script

I've tested this in gmail, yahoo, and hotmail. So far, it worked fine.

code:


function send_email($data, $subject, $content, $attachment = NULL) {

$name_from = $data["name_from"]; // Who the email is from
$email_from = $data["email_from"]; // Who the email is from
$email_to = $data["email_to"]; // Who the email is to
$email_cc = $data["email_cc"]; // Who the email is cc
$email_bcc = $data["email_bcc"]; // Who the email is bcc
$fileatt = $attachment["tmp_name"]; // Path to the file
$fileatt_type = $attachment["type"]; // File Type
$fileatt_name = $attachment["name"]; // Filename that will be used for the file as the attachment
$email_subject = $subject; // The Subject of the email
$email_message = $content; // Message that the email has in it

$semi_rand = md5(time());
$mime_boundary = $semi_rand;

$headers = "From: $name_from<$email_from>\r\n";
$headers .= ($email_bcc != "")? "Bcc: ". $email_bcc ."\r\n" : "";
$headers .= ($email_cc != "")? "Cc: ". $email_cc ."\r\n" : "";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; ";
$headers .= "boundary=".$mime_boundary."\r\n";

// This two steps to help avoid spam
//$headers .= "Message-ID: <".$now." TheSystem@".$_SERVER['SERVER_NAME'].">\r\n";
//$headers .= "X-Mailer: PHP v".phpversion()."\r\n";

$email_message .= "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$email_message . "\n\n";

if (!is_null($attachment)) {
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
} else {
$email_message .= "--{$mime_boundary}--\n";
}
$ok = mail($email_to, $email_subject, $email_message, $headers);
return ($ok)? true : false;
}


note: $data and $attachment are arrays

No comments: