Sending Email with Attachment in PHP

drupal_developer's picture

<?php
if(isset($_POST['submit'])) {
$contact_name = $_POST['contact_name'];
if (isset($_FILES['attachment'])) {
$destination_path = 'upload-files/';
$result = 0;
$target_path = $destination_path . basename( $_FILES['attachment']['name']);
$file_type = $_FILES['attachment']['type'];
$name = $_FILES['attachment']['name'];
if(@move_uploaded_file($_FILES['attachment']['tmp_name'], $target_path)) {
$success = TRUE;
}
}
$body = 'Contact Name: '.$contact_name;
$email_from = "abc@xyz.com";
$email_message = $body;
$email_to = "xyz@yahoo.com"; // Who the email is to
$headers = "From: ABC \n";
$headers .= "Reply-To: XYZ \n";
$headers .= "CC: aca@gmail.com\n";
$headers .= "BCC: 121@gmail.com";
$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 .= "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(isset($_FILES['attachment']) && $success ) {

$fileatt = 'upload-files/'.$name; // Path to the file
$fileatt_name = $name; // Filename that will be used for the file as the attachment
$fileatt_type = $file_type; // File Type

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

}

$ok = @mail($email_to, $email_subject, $email_message, $headers);
if ($ok) {
if(isset($_FILES['attachment']) && $success ) {
unlink($target_path);
}
$msg = "Thank You for Sending Mail.";
}
else {
$msg = "Oops! there were some problems during sending mail, Please try later after some time.";
}

echo $msg;

}
else {
?>
<form action="" id="mailForm" name="mailForm" method="POST" enctype="multipart/form-data">
Contact Name : <input name="contact_name" class="txtbox" id="contact_name" type="text">
Attachment : <input type="file" id="attachment" name="attachment" value="Browse" />
<input value="Send" name="submit" id="submit" type="submit">
</form>
<?php } ?>

 

Free Web Hosting
v>