PHP mail sent before finish uploading the attachment - php

I am making a PHP form which allow users to upload attachment and send it to my e-mail. I have been searching for quite a long time to make it.
And, finally, I found this. http://www.shotdev.com/php/php-mail/php-send-email-upload-form-attachment-file/. It works fine.
However, when I modify it myself (change the fields), something doesn't go well.
<?php
$location=$_POST['location'];
$name_ha=$_POST['name_ha'];
$name_person=$_POST['name_person'];
$email=$_POST['email'];
$date_sent=$_POST['date_sent'];
$date_completed=$_POST['date_completed'];
$date_received=$_POST['date_received'];
$to="admin#admin.com" . "$email";
$message="to";
//*** Uniqid Session ***//
$sid = md5(uniqid(time()));
$header = "";
$header .= "From: ".$_POST["name_ha"]."<".$_POST["email"].">\nReply-To: ".$_POST["email"]."";
$header .= "MIME-Version: 1.0\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$sid."\"\n\n";
$header .= "This is a multi-part message in MIME format.\n";
$header .= "--".$sid."\n";
$header .= "Content-type: text/html; charset=utf-8\n";
$header .= "Content-Transfer-Encoding: 7bit\n\n";
$header .= $message."\n\n";
//*** Attachment ***//
if($_FILES["fileAttach"]["name"] != "")
{
$FilesName = $_FILES["fileAttach"]["name"];
$Content = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));
$header .= "--".$sid."\n";
$header .= "Content-Type: application/octet-eam; name=\"".$FilesName."\"\n";
$header .= "Content-Transfer-Encoding: base64\n";
$header .= "Content-Disposition: attachment; filename=\"".$FilesName."\"\n\n";
$header .= $Content."\n\n";
}
$flgSend = #mail($to,"A new file for you!",null,$header); // # = No Show Error //
if ($flgSend)
{
echo "Mail sent.";
}
?>
The files I downloaded from shotdev.com and the one I modified are being hosted on the same server and under the same folder.
But, for the one I have modified, the email is sent before the attachment is uploaded (~ 45% of the uploading process) if the file size is greater than 1MB. The email I received, there is no attachment and no information of sender ($name_ha).
On the other hand, for the files downloaded on shotdev.com, the email will only be sent after the attachment is uploaded completely no matter how big it is.
Is there any error of the script, or something is missing, causing such an occurrence? Your time and help is much appreciated.

First, in code that you showed as example you have error on this line:
$to="admin#admin.com" . "$email";
Change it to:
$to="admin#admin.com, " . "$email";
Notice comma that you are missing... It needed to be there for every new receivers email you want to add on that particular way...
Also I have tested code on my server, everything works well.
I have 100 mbps upload and tried file that is 4.5 MB and it works.
So maybe there is a problem with your upload speed and allowed execution time of php script that you are calling to send this email.
Try to add the following just after <?php in php file that you setted in HTML form as action="something.php":
set_time_limit(0);
That means that there is no liimt in execution time of script, change 0 to desired number of seconds...
Also remove # before #mail() function if there are errors you need to see them, hiding them will not do any good for you.
EDIT:
I have altered your code so that it does check if, firstly if there is file, if not sends mail without attachment. And if there is file it checks if it is encoded to base64 and splited and in that case it send the mail with attachment...
<?php
$location=$_POST['location'];
$name_ha=$_POST['name_ha'];
$name_person=$_POST['name_person'];
$email=$_POST['email'];
$date_sent=$_POST['date_sent'];
$date_completed=$_POST['date_completed'];
$date_received=$_POST['date_received'];
$FilesName = $_FILES["fileAttach"]["name"];
$to = "admin#mail.com," . "$email";
$message = "to";
$sid = md5(uniqid(time()));
$header = "";
$header .= "From: ".$_POST["name_ha"]."<".$_POST["email"].">\nReply-To: ".$_POST["email"]."";
$header .= "MIME-Version: 1.0\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$sid."\"\n\n";
$header .= "This is a multi-part message in MIME format.\n";
$header .= "--".$sid."\n";
$header .= "Content-type: text/html; charset=utf-8\n";
$header .= "Content-Transfer-Encoding: 7bit\n\n";
$header .= $message."\n\n";
if($_FILES["fileAttach"]["name"] != "") {
$Content = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));
$header .= "--".$sid."\n";
$header .= "Content-Type: application/octet-stream; name=\"".$FilesName."\"\n";
$header .= "Content-Transfer-Encoding: base64\n";
$header .= "Content-Disposition: attachment; filename=\"".$FilesName."\"\n\n";
$header .= $Content."\n\n";
}
if (strlen($FilesName) > 0) {
if ($Content) {
$flgSend = mail($to,"Here is that file",null,$header);
}
else {
echo "problem with file...";
}
}
else {
$flgSend = mail($to,"Here is that file",null,$header);
}
if ($flgSend) {
echo "Mail sent.";
}
?>
HERE IS HTML FOR IT:
<html>
<head>
</head>
<body>
<form method="post" action="sender.php" enctype="multipart/form-data" >
location: <input type="text" name="location" />
<br />
name_ha: <input type="text" name="name_ha" />
<br />
name_person: <input type="text" name="name_person" />
<br />
email: <input type="text" name="email" />
<br />
date_sent: <input type="text" name="date_sent" />
<br />
date_completed: <input type="text" name="date_completed" />
<br />
date_received: <input type="text" name="date_received" />
<br />
file: <input type="file" name="fileAttach" />
<br />
<input type="submit" value="submit" />
</form>
</body>
</html>

Related

How do I rename an uploaded file and send it as an email attachment (PHP)?

I have a php code(example.php) which extracts the email id(sender#example.com) from the following form, gets the uploaded file and sends an email to a recipient#example.com with the uploaded file as attachment and the extracted email id as the sender id. Then it redirects the user to a success.html page.
The html form is as below:
<form action="http://example.com/example.php" enctype="multipart/form-data" method="POST">
<label>Your Email <input name="sender_email" type="email" /> </label></p>
<label>Attachment <input name="my_file" type="file" /></label> <label><input name="button" type="submit" value="Submit" /></label></p>
</form>
<p>
</p>
The php for the form is:
<?php
if($_POST && isset($_FILES['my_file']))
{
$recipient_email = 'recipient#example.com';
//Capture POST data from HTML form and Sanitize them,
$from_email = filter_var($_POST["sender_email"],
FILTER_SANITIZE_STRING); //sender email used in "reply-to" header
$subject = SUBMISSION_PG;
$message = filter_var($_POST["message"],
FILTER_SANITIZE_STRING); //message
//Get uploaded file data
$file_tmp_name = $_FILES['my_file']['tmp_name'];
$file_name = $_FILES['my_file']['name'];
$file_size = $_FILES['my_file']['size'];
$file_type = $_FILES['my_file']['type'];
$file_error = $_FILES['my_file']['error'];
if($file_error > 0)
{
die('Upload error or No files uploaded');
}
//read from the uploaded file & base64_encode content for the mail
$handle = fopen($file_tmp_name, "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content));
$boundary = md5("sanwebe");
//header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:".$from_email."\r\n";
$headers .= "Reply-To: ".$from_email."" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary =
$boundary\r\n\r\n";
//plain 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($message));
//attachment
$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;
$sentMail = #mail($recipient_email, $subject, $body, $headers);
if($sentMail) //output success or failure messages
{
header("Location:http://example.com/success.html");
}else{
die('Could not send mail! Please check your PHP mail
configuration.');
}
}
?>
I need to rename the uploaded filename to sender#example.com.extension then send the uploaded file as attachment.
I'd be thankful to anyone who can solve me this issue.
As found in this answer: https://stackoverflow.com/a/31428803/2311317
On this line:
$body .="Content-Type: $file_type; name=".$file_name."\r\n";
Change to
$body .= "Content-Type: application/octet-stream; name=\"".$file_name."\"\r\n";
Dont forget to escape your double quotes in those lines and others where you place PHP variables.
like this occurance:
name=\"".$file_name."\"\r\n"
Notice the extra quotes and escaped quotes.

Unable to properly add an attachment - part of headers are added to file

I want to send an email with a pdf attachment using PHP's mail(). The problem is that in the end my attachment file is unreadable, because instead of decoding it from base64, part of headers are appended to it. My guess is that I'm concatenating headers in wrong way, but I tried to change it in various ways and result was always the same.
This is the final mail content I get in plain text:
MIME-Version: 1.0
From: XXX - xxxxx <xxxx.xxxx#xxxxx.com>
Content-Type: multipart/mixed; boundary=_x27e6cd8de4c00e2104105d5353947a1b0ca2a770x
This is a MIME encoded message.
--_x27e6cd8de4c00e2104105d5353947a1b0ca2a770x
Content-type: text/plain;charset=utf-8
Verification Email
To activate the account click on the following link or copy-paste it in your browser:
http://10.24.35.92:443/?ctrl=users&act=verify&id=174&hash=4e4b5fbbbb602b6d35bea8460aa8f8e5
--_x27e6cd8de4c00e2104105d5353947a1b0ca2a770x
Content-type: text/html;charset=utf-8
<h4>Verification Email</h4>
<table>
<tr><td>To activate the account click on the following link or copy-paste it in your browser:</td></tr>
<tr><td>http://10.24.35.92:443/?ctrl=users&act=verify&id=174&hash=4e4b5fbbbb602b6d35bea8460aa8f8e5</td></tr>
--_x27e6cd8de4c00e2104105d5353947a1b0ca2a770x
Content-Type: application/pdf; name="xxxx.pdf";
Content-Transfer-Encoding: base64;
Content-Disposition: attachment; filename="xxxx.pdf";
(here goes the encoded attachment)
JVBERi0xLjUNCiW1tbW1DQoxIDAgb2JqDQo8PC9UeXBlL0NhdGFsb2cvUGFnZXMgMiAwIFIvTGFu
MDAwMCBuDQowMDAwMTUzODUwIDAwMDAwIG4NCjAwMDAxNzM4NzUgMDAwMDAgbg0KMDAwMDE3NDEw
MSAwMDAwMCBuDQp0cmFpbGVyDQo8PC9TaXplIDIxOS9Sb290IDEgMCBSL0luZm8gMzEgMCBSL0lE
(...)
--_x27e6cd8de4c00e2104105d5353947a1b0ca2a770x--
and this is how the pdf attachment looks like in text editor:
Content-Transfer-Encoding: base64;
Content-Disposition: attachment; filename="xxxx.pdf"
JVBERi0xLjUNCiW1tbW1DQoxIDAgb2JqDQo8PC9UeXBlL0NhdGFsb2cvUGFnZXMgMiAwIFIvTGFu
Zyhlbi1VUykgL1N0cnVjdFRyZWVSb290IDMyIDAgUi9NYXJrSW5mbzw8L01hcmtlZCB0cnVlPj4+
(...)
You need to use the multipart/mixed MIME type. Something like this should works:
<form name="form1" enctype="multipart/form-data" method="post" action="">
<label for="name">Your Name</label>
<input type="text" id="name" name="name" />
<label for="email">Your Email</label>
<input type="email" id="email" name="email" />
<label for="myfile">Attachment</label>
<input type="file" id="myfile" name="my_file" />
<input type="submit" name="button" value="Submit" />
</form>
PHP CODE
if($_POST && isset($_FILES['my_file'])){
$from_email = 'example#senderMail.com';
$to = 'to_mail#example.com';
$subject = 'Test mail with attachment';
$message = 'This is body of the message';
//get file details we need
$file_tmp_name = $_FILES['my_file']['tmp_name'];
$file_name = $_FILES['my_file']['name'];
$file_size = $_FILES['my_file']['size'];
$file_type = $_FILES['my_file']['type'];
$file_error = $_FILES['my_file']['error'];
$user_email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
if($file_error>0)
{
die('upload error');
}
//read from the uploaded file
$handle = fopen($file_tmp_name, "r");
$content = fread($handle, $file_size);
fclose($handle);
//encode it with MIME base64, and split it into smaller chunks
$encoded_content = chunk_split(base64_encode($content));
//create a boundary string. It must be unique, you can use the MD5 algorithm to generate a random hash
$boundary = md5(date('r', time()));
//header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:".$from_email."\r\n";
$headers .= "Reply-To: ".$user_email."" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
//plain 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($message));
//attachment
$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;
$sentMail = #mail($recipient_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.');
}
}
Hope it helps.
Cheers,
Vince.

php - instead of uploading to folder, send as email with attachment of file uploaded

<?php
//if there is post
if(isset($_POST) && !empty($_POST)){
//if there is attachment
if(!empty($_FILES['attachment']['name'])){
//store some variables
$file_name = $_FILES['attachment']['name'];
$temp_name = $_FILES['attachment']['tmp_name'];
$file_type = $_FILES['attachment']['type'];
//get the extension of the file
$base = basename($file_name);
$extension = substr($base, strlen($base)-4,strlen($base));
//only these file type will be allowed
$allow_extensions = array(".doc","docx",".pdf",".zip",".png");
//check if file is allowes
if(in_array($extension,$allow_extensions)){
//mail essentials
$from = $_POST['email'];
$to = "sampleemail#gmail.com";
$replyto = $to;
$subject = "email with attachment";
$message = "this is a random message";
//things you need
$file = $temp_name;
$content = chunk_split(base64_encode(file_get_contents($file)));
$uid = md5(uniqid(time()));
//standard mail headers
$header = "From " . $from . "\r\n";
$header .= "Reply-To: " . $replyto . "\r\n";
$header .= "MIME-Version: 1.0\r\n";
//declairing we hav e multiple parts of message like text
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format. \r\n";
//plain text part
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
//file attachment
$header .= "--".$uid."\r\n";
$header .= "Content-Type: ".$file_type."; name=\"".$file_name."\"\r\n";
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$file_name."\"\r\n\r\n";
$header .= $content. "\r\n\r\n";
//send mail
if(mail($to, $subject, "", $header)){
echo "Mail Sent";
}
else
{
echo "Failed";
}
}
else{
echo "file type not allowed";
}
}
else{
echo "no file posted";
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="index.php" enctype="multipart/form-data">
<input type="text" name="email" value="from" />
<br>
<input type="file" name="attachment" />
<br>
<input type="submit" value="Send Mail" />
</form>
</body>
</html>
Can't find the bug to my code, I am not getting the link to my attachment.. T_T please help. I am not good in boundary.. T_T I tried using phpmailer but can't get it to work, is there any document to read on how to set it up? I really just wanted to make a simple form with attach button for applicant to sent their resumes..
Everything after $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n"; should be in a $body, not a header.
I would get rid of this: $header .= "This is a multi-part message in MIME format. \r\n";
After $content you actually need to put another line with the mime separator.
$body .= $content . "\r\n" . '--' . $uid . '--';
And finally
if (mail($to, $subject, $body, $header)) {...

Email form sends multiple mails depending on attachments

So basically I want an email system that can send a message with one or more pictures, the problem I have now is that when I upload let's say 4 pictures, the form sends me 4 emails with both the same text but one picture at a time. I want them all to be added as 4 attachments to 1 email, not 1 attachment to 4 emails.
Here is my HTML:
<form id="upload" method="post" action="upload.php">
<div id="drop">
Onderwerp<br>
<input name="txtSubject" type="text" id="txtSubject" /><br>
Omschrijving<br>
<textarea name="txtDescription" cols="30" rows="4" id="txtDescription"></textarea><br>
Voeg afbeeldingen toe
<input type="file" name="fileAttach" multiple accept="image/*;capture=camera" />
<input type="submit" name="Submit" value="Send">
</div>
<ul>
<!-- The file uploads will be shown here -->
</ul>
</form>
and here is my PHP:
<?
$strTo = "email#email.com";
$strSubject = $_POST["txtSubject"];
$strMessage = nl2br($_POST["txtDescription"]);
//*** Uniqid Session ***//
$strSid = md5(uniqid(time()));
$strHeader = "";
$strHeader .= "From: ".$_POST["txtFormName"]."<".$_POST["txtFormEmail"].">\nReply-To: ".$_POST["txtFormEmail"]."";
$strHeader .= "MIME-Version: 1.0\n";
$strHeader .= "Content-Type: multipart/mixed; boundary=\"".$strSid."\"\n\n";
$strHeader .= "This is a multi-part message in MIME format.\n";
$strHeader .= "--".$strSid."\n";
$strHeader .= "Content-type: text/html; charset=utf-8\n";
$strHeader .= "Content-Transfer-Encoding: 7bit\n\n";
$strHeader .= $strMessage."\n\n";
//*** Attachment ***//
if($_FILES["fileAttach"]["name"] != "")
{
$strFilesName = $_FILES["fileAttach"]["name"];
$strContent = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));
$strHeader .= "--".$strSid."\n";
$strHeader .= "Content-Type: application/octet-stream; name=\"".$strFilesName."\"\n";
$strHeader .= "Content-Transfer-Encoding: base64\n";
$strHeader .= "Content-Disposition: attachment; filename=\"".$strFilesName."\"\n\n";
$strHeader .= $strContent."\n\n";
}
$flgSend = #mail($strTo,$strSubject,null,$strHeader); // # = No Show Error //
if($flgSend)
{
echo "Mail send completed.";
}
else
{
echo "Cannot send mail.";
}
?>
I'm not that great with PHP, I took an multiple image uploader and tried to make it into a mailing form, wich works.. except for the multiple email sending part.
Any help is greatly appreciated! :)
try something like:
for($i=0;$i<count($_FILES["fileAttach"]["name"]);$i++)
{
if($_FILES["fileAttach"]["name"][$i] != "")
{
$strFilesName = $_FILES["fileAttach"]["name"][$i];
$strContent = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"][$i])));
$strHeader .= "--".$strSid."\n";
$strHeader .= "Content-Type: application/octet-stream; name=\"".$strFilesName."\"\n";
$strHeader .= "Content-Transfer-Encoding: base64\n";
$strHeader .= "Content-Disposition: attachment; filename=\"".$strFilesName."\"\n\n";
$strHeader .= $strContent."\n\n";
}
}

$_POST - results to be sent in a email

<textarea rows="4" cols="70" name="filename" id="result" style="background:#B0D2D7;
width:100%;overflow:auto;resize:none"
readonly><?php echo $_POST['filename']; ?></textarea>
Hi all, this is a snippet of code I'm using. What I'm struggling with is how to send
the $_POST results that get displayed on the next page into an email using PHP email.
The results are not displayed in a text box as such on the next page but displayed more like a print_pr into a PHP form.
Any help would be great!
To move data across into another page via POST, the easiest way is to wrap your textarea in a form and add a submit button:
<form action="?" method="post">
<textarea name="filename"></textarea>
<input type="submit" />
</form>
<?php
if(isset($_POST["filename"]))
{
echo $_POST["filename"];
}
?>
You also made a vague reference to sending an email, which can be done using the mail() function.
<?
$g_mail = "mail#domain.com";
$s_name = "Some name";
$to = "Receiver <receiver#domain.com>";
$subject = "Some subject";
$message= "HTML codes here. Write anything you want including " . $_POST['data'];
$header = "From: $s_name <".$g_mail.">\n";
$header .= "Reply-To: $s_name <".$g_mail.">\n";
$header .= "Return-Path: $s_name <".$g_mail.">\n";
$header .= "Delivered-to: $s_name <".$g_mail.">\n";
$header .= "Date: ".date(r)."\n";
$header .= "Content-Type: text/html; charset=iso-8859-9\n";
$header .= "MIME-Version: 1.0\n";
$header .= "Importance: Normal\n";
$header .= "X-Sender: $s_name <".$g_mail.">\n";
$header .= "X-Priority: 3\n";
$header .= "X-MSMail-Priority: Normal\n";
$header .= "X-Mailer: Microsoft Office Outlook, Build 11.0.5510\n";
$header .= "X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.2869\n";
mail($to, $subject, $message, $header);
?>
This is the mail script I generally use. It will not be marked as spam on most mail providers aswell.

Categories