Following is the code I am using to send multiple files as attachment in a mail, tested it in local environment, the attachments were reaching the mail box but as empty files, and in live environment, result is mail could not be sent, though files get saved in the upload folder on the server...a newbie in php so please can anyone help what am I doing wrong..??
In local environment i was using this code $server_file = "/localhost:81/xyz/uploads/$path_parts[basename]"; in place what is mentioned down there under move this file to the server
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//did files get sent
if(isset($_FILES) && (bool) $_FILES) {
//define allowed extensions
$allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt");
$files = array();
$username=$_POST['username'];
$email=$_POST['email'];
//loop through all the files
foreach($_FILES as $name=>$file){
//define some variables
$file_name= $file['name'];
$temp_name= $file['tmp_name'];
//check if this file type is allowed
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
die("extension not allowed");
}
//move this file to the server
$server_file = "/home/public_html/xyz.com/uploads/$path_parts[basename]";
move_uploaded_file($temp_name,$server_file);
//add this file to array of files
array_push($files,$server_file);
}
//define some mail variables
$to = "info#xyz.com";
$from = "From: $username<$email>\r\nReturn-path: $email";
$subject = "Photo attachment of . $name .";
$msg = "Images of $username, $email";
$headers = "From: $from";
//define our boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
//tell the header about the boundary
$headers .= "nMIME-Version:1.0\n";
$headers .= "Content-Type: multipart/mixed;\n";
$headers .= " boundary=\"{$mime_boundary}\"";
//part1: define the plain text email
$message = "\n\n--{$mime_boundary}\n";
$message .="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .="Content-Transfer-Encoding: 7bit\n\n". $msg ."\n\n";
$message .="--{$mime_boundary}\n";
//part2: loop and define mail attachments
foreach($files as $file){
$aFile = fopen($file,"rb");
$data = fread($aFile,filesize($file));
fclose($aFile);
$data = chunk_split(base64_encode($data));
$message .="Content-Type: {\"application/octet-stream\"};\n";
$message .= " name=\"$files\"\n";
$message .= "Content-Disposition: attachment;\n";
$message .= " filename=\"$files\"\n";
$message .= "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
//send the email
$ok = mail($to, $subject, $message, $headers, $from);
if($ok){
header("Location: thank-your.php");
}
else{
echo"<p>mail could not be sent!</p>";
}
die();
}
?>
Related
Here are the codes that works by receiving multiple files from HTML form. I need your assistance on how I can do the same while taking attachment files from the same server directory and not from HTML form anymore. Thanks.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_FILES) && (bool) $_FILES) {
$allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt");
$files = array();
foreach($_FILES as $name=>$file) {
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
$file_type = $file['type'];
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
die("File $file_name has the extensions $ext which is not allowed");
}
array_push($files,$file);
}
// email fields: to, from, subject, and so on
$to = "anold#insprogress.com";
$from = "we#insprogress.com";
$subject ="test attachment";
$message = "this is a test message";
$headers = "From: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x]['tmp_name'],"rb");
$data = fread($file,filesize($files[$x]['tmp_name']));
fclose($file);
$data = chunk_split(base64_encode($data));
$name = $files[$x]['name'];
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$name\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$name\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send
$ok = mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>mail sent to $to!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
}
?>
<input type="submit" value="submit"/>
</form>
</body>
As per the question you want to send the attachments available on the server current working directory.
thus the above file upload code can be removed from the code.
if the user wants to see the files present in the server you can make a AJAX request system which will contact the server for the files present in the directory and show them to the user.
for the above task you can refer the Directory Class functions to show the file names over the web page.
the above code for the attachments can be modified as:
$files = //the options selected by the user in an array
//don't forget to sanitize and check the data.
// preparing attachments
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
...
The s_name and s_email fields don't show up in the email sent, only the attachments and message show up. Please assist with any changes to the code to show all form fields in the email.
I have looked at a number of posts but can't seem to find the answer to the problem and assistance will be appreciated.
<?php
if($_POST && isset($_FILES['file'])) {
$recepient_email = "recepient#yourmail.com"; //recepient
$from_email = "info#your_domain.com"; //from email using site domain.
$subject = "Attachment email from your website!"; //email subject line
$sender_name = filter_var($_POST["s_name"], FILTER_SANITIZE_STRING);
//capture sender name
$sender_email = filter_var($_POST["s_email"], FILTER_SANITIZE_STRING); //capture sender email
$sender_message = filter_var($_POST["s_message"], FILTER_SANITIZE_STRING); //capture message
$attachments = $_FILES['file'];
//php validation
if(strlen($sender_name)<4){
die('Name is too short or empty');
}
if (!filter_var($sender_email, FILTER_VALIDATE_EMAIL)) {
die('Invalid email');
}
if(strlen($sender_message)<4){
die('Too short message! Please enter something');
}
$file_count = count($attachments['name']); //count total files attached
$boundary = md5("sanwebe.com");
if($file_count > 0){ //if attachment exists
//header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:".$from_email."\r\n";
$headers .= "Reply-To: ".$sender_email."" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
//message text
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($sender_message));
//attachments
for ($x = 0; $x < $file_count; $x++) {
if(!empty($attachments['name'][$x])) {
if($attachments['error'][$x]>0) { //exit script and output error if we encounter any
$mymsg = array(
1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
3=>"The uploaded file was only partially uploaded",
4=>"No file was uploaded",
6=>"Missing a temporary folder"
);
die($mymsg[$attachments['error'][$x]]);
}
//get file info
$file_name = $attachments['name'][$x];
$file_size = $attachments['size'][$x];
$file_type = $attachments['type'][$x];
//read file
$handle = fopen($attachments['tmp_name'][$x], "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)
$body .= "--$boundary\r\n";
$body .="Content-Type: $file_type; name=\"$file_name\"\r\n";
$body .="Content-Disposition: attachment; filename=\"$file_name\"\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$body .= $encoded_content;
}
}
} else { //send plain email otherwise
$headers = "From:".$from_email."\r\n".
"Reply-To: ".$sender_email. "\n" .
"X-Mailer: PHP/" . phpversion();
$body = $sender_message;
}
$sentMail = #mail($recepient_email, $subject, $body, $headers);
if($sentMail) { //output success or failure messages
die('Thank you for your email');
} else {
die('Could not send mail! Please check your PHP mail configuration.');
}
}
?>
Are you able to see all your form fields doing this?
<?php print_r($_POST); ?>
Double-check if all your form fields has the name attr and if their are matching to fields printed above.
$headers .= "Reply-To: ".$sender_email."" . "\r\n";
You have an extra double quote? Should be like this:
$headers .= "Reply-To:" .$sender_email. "\r\n";
Your $sender_name is not used in the email, only when you check if the length is < 4.
I have a php form which allows multiple uploads of the accepted extentions:
$allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt");
If extention isn't valid it enters this:
if(!in_array($ext,$allowedExtensions)) {
die("File $file_name has the extensions $ext which is not allowed");
}
At the moment I'm getting the error "File has the extensions which is not allowed" when a field is left blank. I have tried adding into the array an empty" ", is that what a blank file's extention would be?
What is the best way around this? Would it be to load in preset image when not filled in or does someone have a solution?
Here is the source code, maybe can help someone else:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_FILES) && (bool) $_FILES) {
$allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt");
$files = array();
foreach($_FILES as $name=>$file) {
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
$file_type = $file['type'];
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
die("File $file_name has the extensions $ext which is not allowed");
}
array_push($files,$file);
}
// email fields: to, from, subject, and so on
$to = "<info#xxx.co.uk>";
$from = "<info#xxx.co.uk>";
$subject ="test attachment";
$message = "this is a test message";
$headers = "From: $from";
$band = $_POST['band'];
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = $band;
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x]['tmp_name'],"rb");
$data = fread($file,filesize($files[$x]['tmp_name']));
fclose($file);
$data = chunk_split(base64_encode($data));
$name = $files[$x]['name'];
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$name\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$name\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send
$ok = mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>photos sent!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
}
?>
This is just a sample of the code, essentially I have a form with 4 files to upload. The files are successfully saved on my server in a designated folder. However, I obviously am not attaching them properly since they are empty....can anyone help?
Also, the attachments disply the directory name instead of the file name...what am I missing?
Many thanks!!!
<?php
$username= protect($_POST['username']);
$firstName= protect($_POST['firstName']);
$lastName= protect($_POST['lastName']);
$email= protect($_POST['email']);
$program= protect($_POST['program']);
$dob= protect($_POST['dob']);
$transcript= $_FILES['transcript'];
$resume= $_FILES['resume'];
$letterIntent= protect($_POST['letterIntent']);
$reference1= $_FILES['reference1'];
$reference2= $_FILES['reference2'];
$relevantExperience= protect($_POST['relevantExperience']);
$volunteerExperience= protect($_POST['volunteerExperience']);
$reasonsAbroad= protect($_POST['reasonsAbroad']);
$definitionSuccess= protect($_POST['definitionSuccess']);
$futureGoals= protect($_POST['futureGoals']);
$challengeYourself= protect($_POST['challengeYourself']);
$challengeDevelopment= protect($_POST['challengeDevelopment']);
if (isset($_FILES) && (bool) $_FILES) {
$allowed_ext = array('doc', 'pdf', 'txt', '');
$files = array();
foreach($_FILES as $name=>$file) {
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$path_parts = pathinfo($file_name);
$file_ext = $path_parts['extension'];
if(!in_array($file_ext, $allowed_ext)) {
die ("extension for file $file_name not allowed");
}
if($file_size > 2097152) {
die ("File size must be under 2MB");
}
$server_file = "wp-content/uploads/application-documents";
move_uploaded_file($file_tmp, "$server_file/$file_name");
array_push($files, $server_file);
}
$to = ".....#gmail.com";
$from = "$email";
$subject ="Application from $firstName $lastName with attachments";
$msg = "hello";
$headers = "From: $from";
//define email boundaries
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n";
$headers .= " boundary=\"{$mime_boundary}\"";
$message ="\n\n--{$mime_boundary}\n";
$message .="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .="Content-Transfer-Encoding: 7bit\n\n" . $msg . "\n\n";
$message .= "--{$mime_boundary}\n";
foreach($files as $file) {
$aFile = fopen($file,"rb");
$data = fread($aFile,filesize($file));
fclose($aFile);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n";
$message .= " name=\"$file\"\n";
$message .= "Content-Disposition: attachment;\n";
$message .= " filename=\"$file\"\n";
$message .= "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
$ok = #mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>mail sent to $to</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
}
}
?>
I know it's not the answer to your post, but after struggling with this kind of problems in the past, I gave up and used PHPMailer. If you still want to roll your own, you should take a look at its source code.
I have an submit page where client scan submit a fillable PDF form along with a photo, using the attached mailer script. The form uploads to the server correctly, however when it is sent to the client, the PDF is blank.
<?php
// did files get sent
if(isset($_FILES) && (bool) $_FILES) {
// define allowed extensions
$allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt");
$files = array();
// loop through all the files
foreach($_FILES as $name=>$file) {
// define some variables
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
// check if this file type is allowed
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
die("extension not allowed");
}
// move this file to the server YOU HAVE TO DO THIS
$server_file = "/home/castmeb1/public_html/uploads/$path_parts[basename]";
move_uploaded_file($temp_name,$server_file);
// add this file to the array of files
array_push($files,$server_file);
}
// define some mail variables
$to = "castmebg#gmail.com";
$from = "castmebg#gmail.com";
$subject ="test attachment";
$msg = "Please see attached";
$headers = "From: $from";
// define our boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// tell the header about the boundary
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n";
$headers .= " boundary=\"{$mime_boundary}\"";
// part 1: define the plain text email
$message ="\n\n--{$mime_boundary}\n";
$message .="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .="Content-Transfer-Encoding: 7bit\n\n" . $msg . "\n\n";
$message .= "--{$mime_boundary}\n";
// part 2: loop and define mail attachments
foreach($files as $file) {
$aFile = fopen($file,"rb");
$data = fread($aFile,filesize($file));
fclose($aFile);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n";
$message .= " name=\"$file\"\n";
$message .= "Content-Disposition: attachment;\n";
$message .= " filename=\"$file\"\n";
$message .= "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send the email
$ok = mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>mail sent to $to!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
die();
}
?>
Thanks,
JB
if(isset($_FILES) && (bool) $_FILES) {
is an invalid test for a successful upload. The $_FILES array is always set, and assuming a file upload ATTEMPT was made, the array will NEVER be empty.
You should check for errors like this:
if ($_FILES['name_of_file_field']['error'] === UPLOAD_ERR_OK) {
... file was successfully uploaded ...
}
The error codes are defined here: http://php.net/manual/en/features.file-upload.errors.php