Trying to send attachments with PHP mail() - php

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

Related

PHP - Attaching Text File - Mail Not Working

I am writing an application that is to send an email that contains a CSV as an attachment. However, it is not working. The mail function does not return false (implying that it succeeded); however, the email is not being sent.
I have sent/received email from the server before, so I do not believe that is the issue. However, I do not really have any experience with sending attachments through PHP, so I would suspect the issue lies in there. I have followed this tutorial to an extent: http://www.texelate.co.uk/blog/post/56-send-an-email-attachment-with-php/
Here are some code snippets:
$file = tmpfile();
// code omitted
$fileArray = array(); // this gets filled with more arrays/lines of data
// code omitted
try {
foreach($fileArray as $line) {
var_dump($line);
fputcsv($file, $line);
}
// begin mailing
$toEmail = 'myemail';
$subject = "Insurance Registration";
fseek($file, 0);
$attachData = fread($file, 1024);
$fileName = $lastName . "_" . date('Y');
$random = md5(time());
$boundary = "==Multipart_Boundary_x{$random}x";
$headers = "From: Test \nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed\n" . "boundary=\"{$boundary}\"";
$message = "Testing!.\n\n " . "-{$boundary}\n " . "Content-Type= text/plain; charset=\"iso-8859-1\n" . "Content-Transfer-Encoding 7bit\n\n " . "Testing Again " . "\n\n ";
$attachData = chunk_split(base64_encode($attachData));
$message .= "--{$boundary}\n" . "Content-Type: text/plain;\n" . "name=\"{$fileName}\"\n" . "Content-Disposition: attachment;\n" . " filename=\"{$fileName}\"\n" . " . Content-Transfer-Encoding: base64\n\n" . $attachData . "\n\n" . "-{$boundary}-\n";
} catch (Exception $e) {
echo $e->getMessage();
}
if(mail($toEmail, $subject, $message, $headers)) {
} else {
$hasError = true;
}
if($hasError) {
echo "<h2>Error Submitting form. Please check your input and try again</h2>";
} else {
header('Location: success.php');
}
I get redirected to the success page, but never receive an email. Thanks!

php mail() function attachment and body both empty

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.

a issue with attachment form

the following code works just fine, but when users submitting without any attachments the page gives error alert and nothing is happened, ther mast any condition that i'm missing, someone knows what i need to add?
<?php
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, array('temp_name' => $temp_name, 'file_name' => $file_name));
}
// email fields: to, from, subject, and so on
$to = "dorozenman#gmail.com";
$from = $_POST['sender_email'];
$subject ="בקשה להצעת עבודה מ" . $_POST['sender_name'] .' '. $_POST['sender_suname'];
$message = 'שם: '. $_POST['sender_name'] . "\r\n" . 'שם משפחה: ' . $_POST['sender_suname'] . "\r\n" . 'תאריך לידה: ' . $_POST['sender_Bday'] . "\r\n" . 'עיסוק נוכחי: ' . $_POST['sender_work'] . "\r\n" . 'טלפון: ' . $_POST['sender_phone'] . "\r\n" . 'מייל: ' . $_POST['sender_email'] . "\r\n" . 'טקסט חופשי: ' . $_POST['sender_way'] ;
$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++){
$temp_name = $files[$x]['temp_name']; // temporary file location
$file_name = $files[$x]['file_name']; // filename
$file = fopen($temp_name,"rb");
$data = fread($file,filesize($temp_name));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$file_name\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$file_name\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send
$ok = #mail($to, $subject, $message, $headers);
if ($ok) { ?>
<script language="javascript" type="text/javascript">
alert('הבקשה נשלחה! שיהיה לך בהצלחה!');
top.window.location = 'https://www.facebook.com/gingereilat';
</script>
<?php } else { ?>
<script language="javascript" type="text/javascript">
alert('שגיאה במערכת בצעו פעולה זאת מאוחר יותר או צרו קשר dorozenman#gmail.com');
top.window.location = 'https://www.facebook.com/gingereilat';
</script>
<?php
}
}
?>
your whole code in following if clause
if(isset($_FILES) && (bool) $_FILES) {
check where its applicable.
Please post the error messages! That makes answering your question a lot easier.
Just reading the code, an obvious problem is var $files is only initialised inside the first if statement, but then you use it in the for loop.
Move the line $files = array(); to the top of your script so it is always initialised as an empty array.

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>";
}
?>

PHP Contact Form w/ File Upload Attachment

I have a simple PHP contact form (Seen Here) that I want to add a file upload option to, so clients can attach an important document and mail it to me using PHP's mail function.
The form works fine on its own, but I can't seem to get the code right for uploading the attachment, storing it temporarily on the server and sending it to me as part of the e-mail. Here is the code I'm using:
<?php
if ($_POST['test'] != '') {
echo 'Unfortunately, by filling out the hidden field, you have been identified as a potential spambot and your message has been terminated.';
} else {
//Validate the name:
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
echo "You forgot to enter your name.<br>";
}
//Validate the phone:
if (!empty($_POST['phone'])) {
$phone = $_POST['phone'];
} else {
echo "You forgot to enter your phone number.<br>";
}
//Validate the e-mail:
if (!empty($_POST['email'])) {
$email = $_POST['email'];
} else {
echo "You forgot to enter your e-mail.<br>";
}
//Validate the message:
if (!empty($_POST['message'])) {
$message = $_POST['message'];
} else {
echo "You forgot to enter a message.";
}
if (!empty($_POST['name']) && !empty($_POST['phone']) && !empty($_POST['email']) && !empty($_POST['message'])) {
// Obtain file upload variables:
$attachment = $_FILES['attachment']['tmp_name'];
$attachment_type = $_FILES['attachment']['type'];
$attachment_name = $_FILES['attachment']['name'];
if (file($attachment)) {
// Read the file to be attached ('rb' = read binary):
$file = fopen($attachment,'rb');
$data = fread($file,filesize($attachment));
fclose($file);
// Generate a boundary string:
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Add the headers for a file attachment:
$headers = "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
// Add a multipart boundary above the plain message:
$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";
// Base64 encode the file data:
$data = chunk_split(base64_encode($data));
// Add file attachment to the message:
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$attachment_type};\n" .
" name=\"{$attachment_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$attachment_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
}
$body = "$name\n$phone\n$email\n\n$message";
mail("*#*.com", "Starcrest Escrow, Inc. Website - Real Property Sale", $body, $headers);
header("Location: confirm.html");
}
}
?>
When I run this script presently, it forwards me to the confirmation page, but no e-mail appears to be generated at all. What am I doing wrong?
<?php
if (isset($_POST['txtEmail'])) {
// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "xyz#abc.com";
$email_subject = "Subject";
$email_from = "abc#xyz.com";
function died($error)
{
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.";
echo $error . "<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if (!isset($_POST['txtName']) || !isset($_POST['txtEmail']) || !isset($_POST['txtAddress']) || !isset($_POST['txtContact']) || !isset($_POST['txtUpload'])) {
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$name = $_POST['txtName']; // required
$email = $_POST['txtEmail']; // required
$address = $_POST['txtAddress']; // required
$contact = $_POST['txtContact']; // not required
$upload = $_POST['txtUpload']; // required
$email_message = "Form Details are below.\n\n";
function clean_string($string)
{
$bad = array(
"content-type",
"bcc:",
"to:",
"cc:",
"href"
);
return str_replace($bad, "", $string);
}
$email_message.= "Full Name: " . clean_string($name) . "\n\n";
$email_message.= "Address: " . clean_string($address) . "\n\n";
$email_message.= "Email ID: " . clean_string($email) . "\n\n";
$email_message.= "Contact No.: " . clean_string($contact) . "\n\n";
$email_message.= "File: " . clean_string($upload) . "\n\n";
// create email headers
$headers = 'From: ' . $email_from . "\r\n" . 'Reply-To: ' . $email . "\r\n" . 'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
<!-- include your own success html here -->
Thank you for contacting us. We will be in touch with you very soon.
<?php
}
?>

Categories