April 25, 2009

Send mail with attachment in php

This code will help you with attachment of files in anytype in sending a mail with php

include this input field inside "form" tag
<input type="file" name="fileatt" size="22" />
<input type="submit" name="career_submit" size="22" />

When the page is submitted use the following code to send the mail to the receipent with the attachment.

if(isset($_REQUEST['career_submit'])) {
/*@@@@@@@@@@@--- File Type --- @@@@@@@@@@@*/
$fileatt_name = $_FILES['fileatt']['name'];
$fileName = $_FILES['fileatt']['tmp_name'];
$fileatt_type = "application/octet-stream";
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/

$email_from = $_REQUEST["email"]; // Who the email is from
$email_subject = "Mail Subject"; // The Subject of the email
$email_to = "example@example.com"; // Who the email is too

$headers = "From: ".$email_from;

/*@@@@@@@--- File Permissions --- @@@@@@@@*/
$file = fopen($fileName,'rw');
@$data = fread($file,filesize($fileName));
@fclose($file);
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/

$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";

$email_message .= 'Your Message.....'; // Mail Content Comes Here

$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";

$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";

$ok = @mail($email_to, $email_subject, $email_message, $headers);
}

No comments:

Post a Comment