php mail() function attachment and body both empty - php

I have been having difficulty trying to debug my php mail() code. I have included the entire PHP block below, so please forgive the formatting and sections that are not relevant (rCaptcha, field validation etc.)
The issue I am having is that when the emails come through... 1) There is no email body... and 2)The attachment is empty.
If I comment out this line "$body .= $my_attachment ;" I receive the expected text in the body, and unsurprisingly no attachment.
Can anyone spot my undoubtedly rookie mistakes?? I am expecting some replies suggesting I use a PHP mail library, which I am investigating now, but for my understanding and education I would appreciate some specific feedback pointing to my mistakes.
Thank you for your help.
<?php
/********************************************
/ Start processing the email
/*******************************************/
# We'll make a list of error messages in an array
$messages = array();
$upload_folder = "uploads/";
// a random hash will be necessary to send mixed content
$separator = md5(time());
// carriage return type (we use a PHP end of line constant)
$eol = PHP_EOL;
// Change this to YOUR address
$recipient = XXX#XXX>COM;
$email = $_POST['myemail'];
$phone = $_POST['phone'];
$realName = $_POST['name'];
$subject = "WEB CONTACT: Careers" ;
$body = "--" . $separator . $eol;
$body .= "FROM: " . $realName .
"\r\nPHONE: " . $phone .
"\r\nEMAIL: " . $email .
"\r\nCONTACT ME VIA: " . $_POST['contact_me'] .
"\r\nMESSAGE:" . $_POST['mymessage'] ;
/********************************************
/ ATTACHMENT
/*******************************************/
//Get the uploaded file information
$name_of_uploaded_file =
basename($_FILES['uploaded_file']['name']);
//get the file extension of the file
$type_of_uploaded_file =
substr($name_of_uploaded_file,
strrpos($name_of_uploaded_file, '.') + 1);
$size_of_uploaded_file =
$_FILES["uploaded_file"]["size"]/1024;//size in KBs
//Settings
$max_allowed_file_size = 1024; // size in KB
$allowed_extensions = array("pdf", "doc", "txt");
//Validations
if($size_of_uploaded_file > $max_allowed_file_size )
{
$messages[] = "Size of file should be less than " . $max_allowed_file_size;
}
//------ Validate the file extension -----
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
{
$allowed_ext = true;
}
}
if(!$allowed_ext)
{
$messages[] = "The uploaded file is not supported file type. ".
" Only the following file types are supported: ".implode(',',$allowed_extensions);
}
//copy the temp. uploaded file to uploads folder
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if(is_uploaded_file($tmp_path))
{
if(!copy($tmp_path,$path_of_uploaded_file))
{
$messages[] = 'Error while copying the uploaded file';
}
}
// attachment
$file = $upload_folder . "/" . $name_of_uploaded_file;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
/***********************************************************
// reCAPTCHA your recaptcha secret key
***********************************************************/
$secretKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
if(isset($_POST['email']))
{
$email=$_POST['email'];
}
if(isset($_POST['comment']))
{
$email=$_POST['comment'];
}
if(isset($_POST['g-recaptcha-response']))
{
$captcha=$_POST['g-recaptcha-response'];
}
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
$messages[] = "The reCaptcha Question was not answered correctly. I am begining to suspect that you are a robot.";
}
/***********************************************************
// END reCAPTCHA
***********************************************************/
/***********************************************************
// Message format validations
***********************************************************/
# Allow only reasonable email addresses
if (!preg_match("/^[\w\+\-.~]+\#[\-\w\.\!]+$/", $email)) {
$messages[] = "That is not a valid email address.";
}
# Allow only reasonable real phone numbers
if (!preg_match("/^[\+0-9\-\(\)\s]*$/", $phone)) {
$messages[] = "The phone number must only include numbers, spaces, brackets(), and '+'.";
}
# Allow only reasonable real names
if (!preg_match("/^[\w\ \+\-\'\"]+$/", $realName)) {
$messages[] = "The real name field must contain only " .
"alphabetical characters, numbers, spaces, and " .
"reasonable punctuation. We apologize for any inconvenience.";
}
# CAREFUL: don't allow hackers to sneak line breaks and additional
# headers into the message and trick us into spamming for them!
$subject = preg_replace('/\s+/', ' ', $subject);
# Make sure the subject isn't blank afterwards!
if (preg_match('/^\s*$/', $subject)) {
$messages[] = "Please choose area and office for your message.";
}
# Make sure the message has a body
if (preg_match('/^\s*$/', $body)) {
$messages[] = "Your message was blank. Did you mean to say " .
"something?";
}
if (count($messages)) {
# There were problems, so tell the user and
# don't send the message yet
foreach ($messages as $message) {
echo("<p>$message</p>\n");
}
echo("<p>Click the back button and correct the problems. " .
"Then click Send Your Message again.</p>");
}
//else
{
# Send the email - we're done
// main header (multipart mandatory)
$headers = "From: " . $realName . $eol;
$headers .= "MIME-Version: 1.0" . $eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
$headers .= "Content-Transfer-Encoding: 7bit" . $eol;
// message
$headers .= "--" . $separator . $eol;
$headers .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
$headers .= "Content-Transfer-Encoding: 8bit" . $eol;
$headers .= $body . $eol;
// attachment
$my_attachment ="";
$my_attachment .= "--" . $separator . $eol;
$my_attachment .= "Content-Type: application/octet-stream; name=\"" . $name_of_uploaded_file . "\"" . $eol;
$my_attachment .= "Content-Disposition: attachment; filename=\"" . $name_of_uploaded_file . "\"" . $eol;
$my_attachment .= "Content-Transfer-Encoding: base64" . $eol;
$my_attachment .= "Content-Disposition: attachment" . $eol;
$my_attachment .= $content . $eol;
$my_attachment .= "--" . $separator . "--";
$body .= $my_attachment ;
mail($recipient,
$subject,
$body,
$headers
);
echo("<p>Your message has been sent. Thank you!</p>\n");
}
?>

You can use PHPmailer class to send the mail. It is very easy option to send mails.
To use PHPMailer:
Download the PHPMailer script from here: http://github.com/PHPMailer/PHPMailer
Extract the archive and copy the script's folder to a convenient place in your project.
Include the main script file -- require_once('path/to/file/class.phpmailer.php');
Now, sending emails with attachments goes from being insanely difficult to incredibly easy:
$email = new PHPMailer();
$email->From = 'you#example.com';
$email->FromName = 'Your Name';
$email->Subject = 'Message Subject';
$email->Body = $bodytext;
$email->AddAddress( 'destinationaddress#example.com' );
$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';
$email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );
return $email->Send();
It's just that one line $email->AddAttachment(); to add an attachment.

Related

PHP: How to send emails with multiple attachments found in the same server

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);
...

Trying to send attachments with PHP mail()

I'm trying to store an uploaded file from a form to the uploads folder as well as send the file as an attachment to an email. The email sends perfectly fine and there is also an attachment, however the attachment is unreadable/corrupted.
I have tried with multiple file types and that makes no difference, I still have the same errors.
<?php
//Store File
if (!empty($_FILES) && isset($_FILES['upload'])) {
switch ($_FILES['upload']["error"]) {
case UPLOAD_ERR_OK:
$target = "uploads/";
$target = $target . basename($_FILES['upload']['name']);
if (move_uploaded_file($_FILES['upload']['tmp_name'], $target)) {
$status = "The file " . basename($_FILES['upload']['name']) . " has been uploaded";
$imageFileType = pathinfo($target, PATHINFO_EXTENSION);
} else {
$status = "Sorry, there was a problem uploading your file.";
}
break;
}
echo "Status: {$status}<br/>\r\n";
}
$fileatt = getcwd() . "/uploads"; // Path to the file
$fileatt_type = "application/pdf"; // File Type
$fileatt_name = $_FILES['upload']['name']; // Filename that will be used for the file as the attachment
$email_from = $_POST['email']; // Who the email is from
$email_subject = "Your attached file"; // The Subject of the email
$email_message = "Thanks for visiting mysite.com! Here is your free file.";
$email_message .= "Thanks for visiting."; // Message that the email has in it
$email_to = 'test#test.com'; // Who the email is to
$headers = "From: " . $email_from;
$file = fopen($fileatt . "/" . $fileatt_name, 'rb');
$data = fread($file, filesize($fileatt . "/" . $fileatt_name));
fclose($file);
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\r\nMIME-Version: 1.0\r\n" . "Content-Type: multipart/mixed;\r\n" . " boundary=\"{$mime_boundary}\"";
$email_message .= "This is a multi-part message in MIME format.\r\n\r\n" . "--{$mime_boundary}\r\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\r\n" . "Content-Transfer-Encoding: 7bit\r\n\r\n" . $email_message .= $_POST['email'] . "<br>" . $_POST['firstname'] . "<br>" . $_POST['surname'] . "<br>" . $_POST['degree'] . "<br>" . "\r\n\r\n";
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\r\n" . "Content-Type: {$fileatt_type};\r\n" . " name=\"{$fileatt_name}\"\r\n" . "Content-Disposition: attachment;\r\n" . " filename=\"{$fileatt_name}\"\r\n" . "Content-Transfer-Encoding: base64\r\n\r\n" . $data .= "\r\n\r\n" . "--{$mime_boundary}--\r\n";
$ok = mail($email_to, $email_subject, $email_message, $headers);
if ($ok) {
echo "You file has been sent
to the email address you specified.
Make sure to check your junk mail!
Click here to return to mysite.com.";
} else {
die("Sorry but the email could not be sent. Please go back and try again!");
}
?>
Please could somebody point me in the right direction?
You can find the solution here.
Explained completely to need to ass same info again.
Solution

How to attach two or multiple files and send mail in PHP [duplicate]

This question already has answers here:
Send attachments with PHP Mail()?
(16 answers)
Sending multiple attachment in an email using PHP
(2 answers)
Closed 4 years ago.
The code below sends only one attachment, but I need to attach and send two file(one rar file and pdf)
$email_to = "$email"; // The email you are sending to (example)
$email_from = "online#example.co.in"; // The email you are sending from (example)
$email_subject = "subject line"; // The Subject of the email
$email_txt = "text body of message"; // Message that the email has in it
$fileatt = "files/example.rar"; // Path to the file (example)
$fileatt_type = "application/x-rar-compressed"; // File Type
$fileatt_name = "example.rar"; // Filename that will be used for the file as the attachment
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers="From: $email_from"; // Who the email is from (example)
$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_txt;
$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-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
mail($email_to,$email_subject,$email_message,$headers);
<form action="#" method="POST" enctype="multipart/form-data" >
<input type="file" name="csv_file[]" />
<br/>
<input type="file" name="csv_file[]" />
<br/>
<input type="file" name="csv_file[]" />
<br/>
<input type="submit" name="upload" value="Upload" />
<br/>
</form>
<?php
if($_POST) {
for($i=0; $i < count($_FILES['csv_file']['name']); $i++){
$ftype[] = $_FILES['csv_file']['type'][$i];
$fname[] = $_FILES['csv_file']['name'][$i];
}
// array with filenames to be sent as attachment
$files = $fname;
// email fields: to, from, subject, and so on
$to = "example#gmail.com";
$from = "example#gmail.com";
$subject ="My subject";
$message = "My 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],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\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>";
}
}
?>
Following the reusability principles, you can use https://github.com/Synchro/PHPMailer
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'jswan'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->From = 'from#example.com';
$mail->FromName = 'Mailer';
$mail->addAddress('josh#example.net', 'Josh Adams'); // Add a recipient
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';
Check the following Multiple file attachment in core php mail function.
<?php
/** Mail with attachment */
function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $bcc, $subject, $message){
$uid = md5(uniqid(time()));
$mime_boundary = "==Multipart_Boundary_x{$uid}x";
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Bcc: ".$bcc."\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$mime_boundary."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$mime_boundary."\r\n";
$header .= "Content-type:text/html; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= nl2br($message)."\r\n\r\n";
$header .= "--".$mime_boundary."\r\n";
foreach($filename as $k=>$v){
$file = $path.$v;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$header .= "Content-Type: application/octet-stream; name=\"".$v."\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$v."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$mime_boundary."--"."\r\n";
}
if (mail($mailto, $subject, "", $header)) {
//echo "mail send ... OK"; // or use booleans here
return true;
} else {
//echo "mail send ... ERROR!";
return false;
}
}
?>
This is one of the best solution i got for multiple mail attachment and tested successfully.
This code gives you freedom by attaching file in email without uploading in your hosting server space. Which is highly needed.
There are many solution telling how to upload files to your server and then send to email, but this solution gives "Direct multiple file attachment to email"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>E-mail with Attachment</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<?php
if ($_SERVER['REQUEST_METHOD']=="POST"){
// we'll begin by assigning the To address and message subject
$to="me#me.com";
$subject="E-mail with attachment";
// get the sender's name and email address
// we'll just plug them a variable to be used later
$from = stripslashes($_POST['fromname'])."<".stripslashes($_POST['fromemail']).">";
// generate a random string to be used as the boundary marker
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
// now we'll build the message headers
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
// here, we'll start the message body.
// this is the text that will be displayed
// in the e-mail
$message="This is an example";
$message .= "Name:".$_POST["fromname"]."Message Posted:".$_POST["modlist"];
// next, we'll build the invisible portion of the message body
// note that we insert two dashes in front of the MIME boundary
// when we use it
$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";
// now we'll process our uploaded files
foreach($_FILES as $userfile){
// store the file information to variables for easier access
$tmp_name = $userfile['tmp_name'];
$type = $userfile['type'];
$name = $userfile['name'];
$size = $userfile['size'];
// if the upload succeded, the file will exist
if (file_exists($tmp_name)){
// check to make sure that it is an uploaded file and not a system file
if(is_uploaded_file($tmp_name)){
// open the file for a binary read
$file = fopen($tmp_name,'rb');
// read the file content into a variable
$data = fread($file,filesize($tmp_name));
// close the file
fclose($file);
// now we encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
}
// now we'll insert a boundary to indicate we're starting the attachment
// we have to specify the content type, file name, and disposition as
// an attachment, then add the file content.
// NOTE: we don't set another boundary to indicate that the end of the
// file has been reached here. we only want one boundary between each file
// we'll add the final one after the loop finishes.
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n";
}
}
// here's our closing mime boundary that indicates the last of the message
$message.="--{$mime_boundary}--\n";
// now we just send the message
if (#mail($to, $subject, $message, $headers))
echo "Message Sent";
else
echo "Failed to send";
} else {
?>
<p>Send an e-mail with an attachment:</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"
enctype="multipart/form-data" name="form1">
<p>Your name: <input type="text" name="fromname"></p>
<p>Your e-mail: <input type="text" name="fromemail"></p>
<p>Mod List: <textarea name="question" maxlength="1000" cols="25" rows="6" name="modlist"></textarea>
<p>File: <input type="file" name="file1"></p>
<p>File: <input type="file" name="file2"></p>
<p>File: <input type="file" name="file3"></p>
<p>File: <input type="file" name="file4"></p>
<p>File: <input type="file" name="file5"></p>
<p>File: <input type="file" name="file6"></p>
<p>File: <input type="file" name="file7"></p>
<p>File: <input type="file" name="file8"></p>
<p><input type="submit" name="Submit" value="Submit"></p>
</form>
<?php } ?>
</body>
</html>
Simple working and tested example:
<?php
mail_attachment("mail#mail.com","Subject","Here is the body",array("file1.pdf","file2.pdf"));
function mail_attachment($to, $subject, $message, $files) {
$headers = "From: no-reply#mail.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}\"";
$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" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
foreach ($files as $file) {
$filename = end(explode("/",$file));
$data = file_get_contents($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$file\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$file\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
echo (#mail($to, $subject, $message, $headers)) ? "<p>Send to $to!</p>" : "<p>Not send toaar $to!</p>";
} // mail-attachment
?>
Try this out. Put your files in an array, then using a form loop add each of them in the $email_message variable
$email_to = "$email"; // The email you are sending to (example)
$email_from = "online#example.co.in"; // The email you are sending from (example)
$email_subject = "subject line"; // The Subject of the email
$email_message = "text body of message"; // Message that the email has in it
$files = array("file_1.ext","file_2.ext","file_3.ext",......);
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers="From: $email_from"; // Who the email is from (example)
$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_txt;
$email_message .= "\n\n";
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$email_message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$email_message .= "--{$mime_boundary}\n";
}
mail($email_to,$email_subject,$email_message,$headers);
Hope it works fine :)
This is the code I am using to send multiple attachments, I hope this helps you too. You actually need to use a loop at attach multiple files.
$files = array("file1.pdf","file2.pdf");
$body = "email in html form";
// email fields: to, from, subject, and so on
$to = "e-mail id of person you are sending to";
$from = "your e-mail id";
$subject = "email subject";
$message = html_entity_decode($body);
$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/html; 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], "rb");
$data = fread($file, filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\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="file" name="file" multiple> //select multiple file
$target_dir = "upload/"; //first upload your directory path
$names = $_FILES['file']['name']; //file Name
$i =0;
foreach($names as $name){
$target_file = $target_dir . basename($name); //first upload your
directory path
move_uploaded_file($_FILES["file"]["tmp_name"][$i], $target_file);
//upload your directory
$mail->addAttachment($target_file); //after upload file path
fetch and atachment
$i++;
}
FYI, this line from the original post, as well as some of the answers, will cause a problem on some email systems.
$headers .= "\nMIME-Version: 1.0\n" .
The \n at the beginning caused the attachments to fail when sending to an address hosted at emailpros.com, a secure HIPAA compliant email system. Simply removing the line break fixed the issue there. However, it had been working just fine when sending to a Gmail account and another host (Hostmonster).
This way worked just fine on all of them.
$headers .= "MIME-Version: 1.0\n" .
<?php
// upload recommendation file section
$target_dir = "wp-content/uploads/rec_file/";
$target_file = $target_dir . basename($_FILES["RC_file"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["RC_file"]["tmp_name"]);
if($check !== false) {
$error_msg = "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
$error_msg = "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
$error_msg = "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["RC_file"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$error_msg = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$error_msg = "your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["RC_file"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["RC_file"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file. ". $error_msg ;
}
}
// upload driven licence file section
$DL_target_dir = "wp-content/uploads/rec_file/";
$DL_target_file = $DL_target_dir . basename($_FILES["DL_file"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($DL_target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["DL_file"]["tmp_name"]);
if($check !== false) {
$error_msg = "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
$error_msg = "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($DL_target_file)) {
$error_msg = "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["DL_file"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$error_msg = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$error_msg = "your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["DL_file"]["tmp_name"], $DL_target_file)) {
echo "The file ". basename( $_FILES["DL_file"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file. ". $error_msg ;
}
}
// array with filenames to be sent as attachment
$files = array($target_file,$DL_target_file);
// email fields: to, from, subject, and so on
$to = "tkdilankumara#gmail.com";
$from = "help#soosti.com";
$subject ="Member Registration";
$headers = "From: $from";
$eol = "\r\n";
$message .= "Member Registration Information.".$eol;
$message .= $username.$eol;
$message .= $email.$eol;
$message .= $Fname.$eol;
$message .= $Lname.$eol;
$message .= $address.$eol;
// 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],"rb");
//$data = #fread($file,filesize($files[$x]));
//#fclose($file);
$content =file_get_contents($files[$x],"rb");
$content = chunk_split(base64_encode($content));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $content . "\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>";
}
?>

Make Attachment File Format only .txt .doc .docx

I create a PHP contact form with file attachment with helping a online tutorial. But i want to function it like user only upload .txt .doc .docx file format, no other format will be accepted.
<?php
$from = "name#example.com";
$to = $_POST['email'];
$subject =$_POST['subject'];
$message = $_POST['body'];
// Temporary paths of selected files
$file1 = $_FILES['file1']['tmp_name'];
$file2 = $_FILES['file2']['tmp_name'];
$file3 = $_FILES['file3']['tmp_name'];
// File names of selected files
$filename1 = $_FILES['file1']['name'];
$filename2 = $_FILES['file2']['name'];
$filename3 = $_FILES['file3']['name'];
// array of filenames to be as attachments
$files = array($file1, $file2, $file3);
$filenames = array($filename1, $filename2, $filename3);
// include the from email in the headers
$headers = "From: $from";
// boundary
$time = md5(time());
$boundary = "==Multipart_Boundary_x{$time}x";
// headers used for send attachment with email
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$boundary}\"";
// multipart boundary
$message = "--{$boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$boundary}\n";
// attach the attachments to the message
for($x=0; $x<count($files); $x++){
$file = fopen($files[$x],"r");
$content = fread($file,filesize($files[$x]));
fclose($file);
$content = chunk_split(base64_encode($content));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$filenames[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $content . "\n\n";
$message .= "--{$boundary}\n";
}
// sending mail
$sendmail = mail($to, $subject, $message, $headers);
// verify if mail is sent or not
if ($sendmail) {
echo "Sent successfully!";
} else {
echo "Error occurred. Try again!";
}
?>
the use of $_FILE["filename"]["type"] is not recomended for file type checking as the type parameter is browser specific i.e different browser can have different type So we will try to extract the format from the string function
$filename=$_FILES["file1"]["name"];//get the name of the file
$extension=strrchr($filename, ".");//extracting the extension
if($extension=".txt" || $extension=".doc" || $extension=".docx")
{
//send mail;
}
else
{
//error;
}
Simply,
$filename_array = explode(".",$filename);
$ext = ".".$filename_array[count($filename_array)-1];
if($ext!==".txt" && $ext!==".doc" && $ext!==".docx"):
//Do bad extension code
endif;
//Do code that passed extension validation
Hope this helps!
$allowed = array('.txt', '.doc', '.docx')
$fileNames = array();
$filename1= $_FILES['file1']['name'];
$ext1 = pathinfo($path, PATHINFO_EXTENSION);
if(in_array($ext1, $allowed)){
array_push($fileNames, $filename1); //repeat for 2, 3, etc...
}
function allowed_file(){
//Add the allowed mime-type files to an 'allowed' array
$allowed = array('application/doc', 'application/txt', 'another/type');
//Check uploaded file type is in the above array (therefore valid)
if(in_array($_FILES['file']['name'], $allowed))
{
// Your code
}
}
Reference : php file upload, how to restrict file upload type

PHP Contact Form - Image uploading to temp but not attatching to email

I was just wondering if anyone could help out with what should be a fairly simple fix (obviously not for me) for a contact form with image upload. The image DOES get uploaded to the temporary folder, but doesn't appear when I receive the email into my account.
I think the form is nearly there, just can't figure out why the image is not attatching to the email when i receive it - guessing the problem is somewhere in the last 10 lines of code.
I would really appreciate if someone could figure what's going wrong.
<?php
ini_set("sendmail_from", "darren#mywebsite.co.uk");
ini_set("SMTP", "smtp.myhostingcompany.co.uk");
if($name = filter_var($_POST['name']))
if($address = filter_var($_POST['address']))
if($postcode = filter_var($_POST['postcode']))
if($phone = filter_var($_POST['phone']))
if($email = filter_var($_POST['email']))
if($details = filter_var($_POST['details']))
if($contactby = filter_var($_POST['contactby']))
/* Subject and Email Destinations */
$emailSubject = 'Work Email!';
$webMaster = 'darren#mywebsite.co.uk';
/* Gathering Data Variables */
$nameField = $_POST['name'];
$addressField = $_POST['address'];
$postcodeField = $_POST['postcode'];
$phoneField = $_POST['phone'];
$emailField = $_POST['email'];
$detailsField = $_POST['details'];
$contactbyField = $_POST['contactby'];
$allowed_filetypes = array('.jpg','.gif','.bmp','.png');
$max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB)
$upload_path = './uploads/';
$filename = $_FILES['userfile']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))
echo 'Your file upload was successful, view the file <a href=
"' . $upload_path . $filename . '" title="Your File">here</a>'; // It worked.
else
echo 'There was an error during the file upload. Please try again.'; // It failed
$body = <<<EOD
Name: $name
Address: $address
Postcode: $postcode
Phone: $phone
Email: $email
Details: $details
Contactby: $contactby
EOD;
$headers = "From: $email\r\n";
$headers .= "Contact-type: text/html\r\n";
$attachment = chunk_split(base64_encode(file_get_contents($temp_file)));
$tmp_file = $_FILES['userfile']['tmp_name'];
$success = mail($webMaster, $attatchment, $body, $headers, "-fdarren#mywebsite.co.uk");
/* Results rendered as HTML */
$theResults = <<<EOD
SENT SENT SENT
EOD;
echo "$theResults"
?>
Your mail headers are wrong, you need to use MIME to define the different content types (The body of the email and the attachment).
I have some code somewhere that I use for emailing uploads, if this isn't answered for you in about 10-20 minutes I'll try and find it for you.
Good luck!
I managed to dig up the code! It's not the cleanest code ever but it gets the job done. There will be a few tweaks you will have to do as this was originally written to email CSV files, but I've commented it all as much as I can for you.
//The recipient(s) who will receive this email.
$mail_recipients = 'example#email.com';
//This is the subject line of the email.
$mail_subject .= 'A new CVS has arrived!';
//This is the emails body.
$message .= 'A new CVS file has been generated and sent to you, please find it attached to this email. <br />';
//This is the full path to the file you want to attach.
$full_path = '/example/path/file.csv';
//The file type of the attachment.
$file_type = 'text/csv';
//Create a file handle to open the file.
$file = fopen($full_path,'rb');
//Read all of the files contents into a variable.
$data = fread($file, filesize($full_path));
//encode and split the contents.
$data = chunk_split(base64_encode($data));
//Close the file, we don't need it anymore!
fclose($file);
//Create a unique boundary
$new_boundary = md5(time());
//This is your basic header information such as who the email is from and the date it was sent.
$mail_header .= 'From: CSV Admin <noreply#website.co.uk>' . "\r\n";
$mail_header .= 'Date: ' . date('r') . "\r\n";
//This part of the header first defines to the email client that it is a multipart message and adds the emails content/body.
$mail_header .= 'Content-Type: multipart/mixed; boundary="' . $new_boundary . '"' . "\r\n\r\n";
$mail_header .= 'MIME-Version: 1.0' . "\r\n";
$mail_header .= 'This is a multi-part message in MIME format' . "\r\n";
$mail_header .= '--' . $new_boundary . "\r\n";
$mail_header .= 'Content-Type:text/html; charset="iso-8859-1"' . "\r\n";
$mail_header .= 'Content-Transfer-Encoding: 7bit' . "\r\n\r\n";
$mail_header .= $message . "\r\n\r\n";
//This part of the header is for the attachment and includes the contents of the file, the files name and other information.
$mail_header .= '--' . $new_boundary . "\r\n";
$mail_header .= 'Content-Type: ' . $file_type . '; name="' . $file_name . '"' . "\r\n";
$mail_header .= 'Content-Transfer-Encoding: base64' . "\r\n";
$mail_header .= 'Content-Disposition: attachment; filename="' . $file_name . '"' . "\r\n\r\n";
$mail_header .= $data . "\r\n\r\n";
//This is needed to stop any rendering errors by email clients and signifies the end of the emails header.
$mail_header .= '--' . $new_boundary . '--' . "\r\n";
//This mails out all of the above.
mail($mail_recipients, $mail_subject, '', $mail_header);
//And we should be done!
Like the guys said your content type is incorrect and you have:
$attachment = chunk_split(base64_encode(file_get_contents($temp_file)));
$tmp_file = $_FILES['userfile']['tmp_name'];
It should be
$tmp_file = $_FILES['userfile']['tmp_name'];
$attachment = chunk_split(base64_encode(file_get_contents($temp_file)));
You have three distinct errors:
The headers for multipart email are a bit more complex.
The parameters to the mail function are incorrect.
You’re passing an undefined variable to file_get_contents.
$mime_boundary = md5(time());
$headers = "From: $email\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed;\r\n";
$headers .= "--".$mime_boundary."--\r\n";
$message .= "This is a multi-part message in MIME format.\r\n\r\n";
$message .= "--".$mime_boundary."--\r\n";
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n";
$message .= "\r\n";
$message .= "$body\r\n";
$message .= "--".$mime_boundary."--\r\n";
$message .= chunk_split(base64_encode(file_get_contents($_FILES['userfile']['tmp_name'])));
mail($webMaster, 'email subject text', $message, $headers);
SitePoint has an in-depth article on Advanced email in PHP Article that you may find beneficial.

Categories