Multiple file upload together with excel form [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
We presently have a form that when submitted the user responses are emailed to us as an attached excel file. We also have another form that allows the user to upload multiple files of various types which are then emailed to us as attachments. However we have been unable to combine the two into one form, so that we can receive an email with both types of attachments. We are beginners...
Below is:
1. The existing form which attaches the single excel content
2. the existing mailer.php
3. the existing form which uploads multiple files
1. excel content form
<?php
error_reporting(E_ALL ^ E_NOTICE);
ob_start();
$taxyear = $_POST['taxyear'];
$company = $_POST['company'];
$tfn = $_POST['tfn'];
$director1 = $_POST['director1'];
$director2 = $_POST['director2'];
$email = $_POST['email'];
?>
<html>
<body>
<form>
<table width="720" border="0" align="center" bgcolor="#FFFFFF">
<tr align="center" valign="top">
<td height="1730">COMPANY RETURN
<table width="702" border="1" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
<tr>
<td colspan="6" align="left" class="whiteonred" >Company <strong><? echo $taxyear; ?> </strong></td>
</tr>
<tr class="excel7" style="height:18.0pt;">
<td colspan="4" align="left" class="centgothicstd" ><strong>PRINCIPAL DETAILS </strong></td>
<td colspan="2" align="right" class="centgothicsm"> </td>
</tr>
<tr style="height:18.0pt;">
<td align="left" class="centgothicsm" >COMPANY NAME & TFN</td>
<td colspan="3" align="left" class="borders"><strong><? echo $company; ?></strong></td>
<td colspan="2" align="left" class="borders"><strong><? echo $tfn; ?></strong></td>
</tr>
<tr style="height:18.0pt;">
<td width="213" align="left" class="centgothicsm" style="height:18.0pt;">DIRECTOR NAMES</td>
<td colspan="3" align="left" class="borders"><? echo $director1; ?></td>
<td colspan="2" align="left" class="borders"><? echo $director2; ?></td>
</tr>
<tr style="height:18.0pt;">
<td width="213" align="left" class="centgothicsm" style="height:18.0pt;">EMAIL ADDRESS</td>
<td colspan="5" align="left" class="borders"><? echo $email; ?></td>
</tr>
</table></td>
</tr>
</table>
</form>
</body>
</html>
<?php
$FILE_CONTENTS = ob_get_contents();
ob_clean();
include("mailer.php");
$recipient = "darren#eto.net.au";
$subject = "Company submission";
$myEmail = new EPDEV_Emailer($recipient, $email, $subject);
$myEmail->addFile("{$company}-{$taxyear}.xls", "application/vnd.ms-excel", $FILE_CONTENTS);
$myEmail->send();
Header("Location: thankyouapplic.htm");
?>
*2. the mailer.php code *
<?php
class EPDEV_Emailer
{
var $message;
var $FILES;
var $EMAIL;
function EPDEV_Emailer($to_address, $from_address, $subject, $reply_address=null, $mailer=null, $custom_header=null)
{
$this->EMAIL = array(
"to" => $to_address,
"from" => $from_address,
"subject" => $subject,
"reply" => (empty($reply_address) ? $from_address : $reply_address),
"mailer" => (empty($mailer) ? "X-Mailer: PHP/" . phpversion() : $mailer),
"header" => (empty($custom_header) ? "" : $custom_header),
"boundary" => "_mimeboundary_".md5(uniqid(mt_rand(), 1))
);
$this->message = "";
$this->FILES = array();
}
function addFile($filename, $type=null, $filecontents=null)
{
if ($filecontents !== null)
{
$index = count($this->FILES);
$this->FILES[$index]['data'] = chunk_split(base64_encode($filecontents));
$this->FILES[$index]['name'] = basename($filename);
if (empty($type))
$this->FILES[$index]['mime'] = mime_content_type($filename);
else
$this->FILES[$index]['mime'] = $type;
}
else if (file_exists($filename))
{
$index = count($this->FILES);
$this->FILES[$index]['data'] = chunk_split(base64_encode(file_get_contents($filename)));
$this->FILES[$index]['name'] = basename($filename);
if (empty($type))
$this->FILES[$index]['mime'] = mime_content_type($filename);
else
$this->FILES[$index]['mime'] = $type;
}
else
{
$this->Error_Handle("File specified -- {$filename} -- does not exist.");
}
}
function addText($text)
{
$this->message .= $text;
}
function getHeader()
{
$header = "From: {$this->EMAIL['from']}\r\n"
. "Reply-To: {$this->EMAIL['reply']}\r\n"
. "X-Mailer: {$this->EMAIL['mailer']}\r\n"
. "MIME-Version: 1.0\r\n"
. "Content-Type: multipart/mixed; boundary=\"{$this->EMAIL['boundary']}\";\r\n";
return $header;
}
function getEmail()
{
$content .= "--{$this->EMAIL['boundary']}\r\n"
. "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n"
. "Content-Transfer-Encoding: 7bit\r\n\r\n"
. $this->message . "\r\n";
if (!empty($this->FILES))
{
foreach($this->FILES as $file)
{
$content .= "--{$this->EMAIL['boundary']}\r\n"
. "Content-Type: {$file['mime']}; name=\"{$file['name']}\"\r\n"
. "Content-Transfer-Encoding: base64\r\n"
. "Content-Disposition: attachment\r\n\r\n"
. $file['data'] . "\r\n";
}
}
$content .= "--{$this->EMAIL['boundary']}--\r\n";
return $content;
}
function send()
{
$result = mail($this->EMAIL['to'], $this->EMAIL['subject'], $this->getEmail(), $this->getHeader());
if (!$result)
$this->Error_Handle("The email failed to send.");
}
function Error_Handle($error)
{
die($error);
}
}
3. the upload form
<body>
<td height="353" colspan="9" align="left" valign="top">
<form enctype="multipart/form-data" name="send" method="post" action="<?=$_SERVER['PHP_SELF']?>">
<input type="hidden" name="action" value="send" />
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
<tr>
<td width="300" align="center"> </td>
<table width="500" height="407" border="0" align="center">
<tr>
<td width="120" align="left" class="indextextlight">Name:</td>
<td colspan="2"><input name="fname" type="text" class="indextextlight" size="30" /></td>
</tr>
<tr>
<td width="120" height="24" align="left" class="indextextlight">E-mail:</td>
<td colspan="2"><label>
<input name="email" type="text" class="indextextlight" size="30" />
</label></td>
</tr>
<tr>
<td width="120" align="left" class="indextextlight">Telephone:</td>
<td colspan="2"><label>
<input name="tel" type="text" class="indextextlight" id="tel" value="" size="15" />
</label></td>
</tr>
<tr>
<td width="120" align="left" valign="top" class="indextextlight">Message:
</td>
<td colspan="2" valign="top"><textarea name="comments" " id="comments" cols="45" rows="4"></textarea></td>
</tr>
<tr>
<td width="120" valign="middle" class="indextextlight">Upload Files:</td>
<td colspan="2"><p>
<input name="attachment[]" type="file" multiple="" class="indextextlight" size="42">
<br />
<span class="centgothicmini"> note - hold the Ctrl key to select multiple files</span><br />
<span class="centgothicmini"> note - max total size of all files can not exceed 10mb</span></td>
</tr>
<tr>
<td width="120" align="left" class="indextextlight">Send:</td>
<td colspan="2" align="left"><input type="image" name="submit" value="Send Email" src="images/btnSubmit.gif" /></td>
</tr>
<tr>
<td width="120" class="indextextlight">Result:</td>
<td colspan="2" class="header"><?php
/* Mailer with Attachments */
$action = $_REQUEST['action'];
global $action;
function showform(){
?></td>
</tr>
<tr>
<td class="indextextlight"> </td>
<td colspan="2" class="header"> </td>
</tr>
<tr><td colspan="3" align="right" valign="baseline" class="footer"><span class="footerheadings"> </span> © 2009-13 BC Accountants Australia Pty Ltd</td>
</tr>
</table>
</form>
<script type="text/javascript">
var frmvalidator = new Validator("send");
frmvalidator.addValidation("fname","req","Please enter your Name");
frmvalidator.addValidation("email","maxlen=50");
frmvalidator.addValidation("email","req");
frmvalidator.addValidation("email","email");
frmvalidator.addValidation("tel","maxlen=15");
frmvalidator.addValidation("tel","numeric");
</script>
<?php
}
function sendMail() {
if (!isset ($_POST['email'])) { //Oops, forgot your email addy!
die ("<p>Oops! You forgot to fill out the email address! Click on the back arrow to go back</p>");
}
else {
$fname = stripslashes($_POST['fname']);
$email = $_POST['email'];
$phone = $_POST['tel'];
$comments = stripslashes($_POST['comments']);
$headers .= "\n";
//Uniqid session
$strSid = md5(uniqid(time()));
//Let's start our headers
$headers = "From: $fname<" . $_POST['email'] . ">\n";
$headers .= "Reply-To: <" . $_POST['email'] . ">\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"".$strSid."\"\n\n";
$headers .= "This is a multi-part message in MIME format.\n";
$headers .= "--".$strSid."\n";
$headers .= "Content-type: text/html; charset=utf-8\n";
$headers .= "Content-Transfer-Encoding: 7bit\n\n";
/* Add our message, in this case it's plain text. You could also add HTML by changing the Content-Type to text/html */
$headers .= "<table>";
$headers .= "<tr><td>CONTACT FORM</td><td> </td></tr>";
$headers .= "<tr><td>Check for attachments</td><td> </td> </tr>";
$headers .= "<tr>
<td> </td>
<td > </td>
</tr>";
$headers .= "<tr>
<td >Name: " . strip_tags($_POST["fname"]) . "</td><td > </td>
</tr>";
$headers .= "<tr>
<td>Email: " . strip_tags($_POST["email"]) . "</td><td > </td>
</tr>";
$headers .= "<tr>
<td>Phone: " . strip_tags($_POST["phone"]) . "</td><td> </td>
</tr>";
$headers .= "<tr>
<td> </td>
<td > </td>
</tr>";
$headers .= "<tr>
<td>MESSAGE</td><td> </td></tr>";
$headers .= "<tr> <td COLSPAN = '2'>" . strip_tags($_POST["comments"]) . "</td>
</tr>";
$headers .= "<tr>
<td> </td>
<td > </td>
</tr>";
$headers .= "</table>";
$headers .= "</body></html>";
$headers .= "\n";
//**multi attach**//
for($i=0;$i<count($_FILES["attachment"]["name"]);$i++)
{
if($_FILES["attachment"]["name"][$i] != "")
{
$file_name = $_FILES["attachment"]["name"][$i];
$data = chunk_split(base64_encode(file_get_contents($_FILES["attachment"]["tmp_name"][$i])));
$headers .= "--".$strSid."\n";
$headers .= "Content-Type: application/octet-stream;\n\tname=\"" . $file_name . "\"\n";
$headers .= "Content-Transfer-Encoding: base64\n";
$headers .= "Content-Disposition: attachment;\n\tfilename=\"" . $file_name . "\"\n\n";
$headers .= $data."\n\n"; //The base64 encoded message
}
}
$headers .= "\n";
$headers .= "------=MIME_BOUNDRY_main_message--\n";
$subject .= "Contact Form";
// send the message
mail("darrenmillbca#gmail.com", $subject, $message, $headers);
print "Mail sent. Thank you!";
$to = $email;
$subject = "Contact Form";
$message = '
<html>
<body>
<p>Dear ';
$message .= $fname;
$message .= '</p>
<p>Thankyou for your message. </p>
<p>Our staff will get back to you shortly. </p>
<p>Kind Regards <br />
<br />
</p>
</body>
</html>
';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To:' . "\r\n";
$headers .= 'From: darrenmillbca#gmail.com' . "\r\n";
//$headers .= 'Cc: birthdayarchive#example.com' . "\r\n";
//$headers .= 'Bcc: birthdaycheck#example.com' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
}
}
switch ($action) {
case "send":
sendMail();
showForm();
break;
default:
showForm();
}
?>
</html>

What you're asking for is quite a significant change here, so I'll try my best to make it simple for you guys. Your excel content form makes use of an email wrapper (mailer.php) which converts attaching files to an email to just $myEmail->addFile("file name","mimetype","file content"). The upload form on the other hand is not using this wrapper and is instead generating a whole email seperately. So you'll want to focus on moving your uploads to utilising the wrapper; that's moving content from the uploads form to the excel form.
So, our focus is with the following block from the uploads file:
for($i=0;$i<count($_FILES["attachment"]["name"]);$i++)
{
if($_FILES["attachment"]["name"][$i] != "")
{
$file_name = $_FILES["attachment"]["name"][$i];
$data = chunk_split(base64_encode(file_get_contents($_FILES["attachment"]["tmp_name"][$i])));
$headers .= "--".$strSid."\n";
$headers .= "Content-Type: application/octet-stream;\n\tname=\"" . $file_name . "\"\n";
$headers .= "Content-Transfer-Encoding: base64\n";
$headers .= "Content-Disposition: attachment;\n\tfilename=\"" . $file_name . "\"\n\n";
$headers .= $data."\n\n"; //The base64 encoded message
}
Which is saying 'for each file upload, write it into the email we're building up'. Instead of this, we want to do 'for each file upload, attach it using the wrapper'. That would be done like so:
for($i=0;$i<count($_FILES["attachment"]["name"]);$i++){
if($_FILES["attachment"]["name"][$i] != "")
{
$file_name = $_FILES["attachment"]["name"][$i];
$data = file_get_contents($_FILES["attachment"]["tmp_name"][$i]);
$myEmail->addFile($file_name,"application/octet-stream",$data);
}
}
For this to work, the above code would go in your excel form right after the existing $myEmail->addFile call. In other words, right after you attach your excel sheet, look for any attachments, then add those to the email too:
$myEmail->addFile("{$company}-{$taxyear}.xls", "application/vnd.ms-excel", $FILE_CONTENTS);
// Drop it right here.
$myEmail->send();
So far so good - at this point, your excel form can handle multiple uploads, but it can't create them. To fix that, you'll then want to start transferring the html that allows your users to upload files over to your excel form. That's this part:
<tr>
<td width="120" valign="middle" class="indextextlight">Upload Files:</td>
<td colspan="2"><p>
<input name="attachment[]" type="file" multiple="" class="indextextlight" size="42">
<br />
<span class="centgothicmini"> note - hold the Ctrl key to select multiple files</span><br />
<span class="centgothicmini"> note - max total size of all files can not exceed 10mb</span></td>
</tr>
<tr>
A simple thing you could do is dump that wherever it fits on your excel form and as a result your excel form should then accept multiple uploads. From there, all that is required is transferring any other fields you want from upload to excel :)

Related

Tell a friend script not sending email php [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
I am trying to execute "Tell a friend" php script, but that is not sending any emails, not to admin, friends, sender. Other emails on same server working fine.
I don't understand why this is not working, as other emails pages like contact us, registration (which send confimation email) all working on same server, please help me..
Html Code:
<table>
<tr>
<td>
<span>Complete the details below to send this link to a friend:</span>
<?php
$refurl = $_SERVER['HTTP_REFERER'];?>
<span><? print $refurl;?></span>
<form name="tellafriend" action="send_group.php" method="post" onSubmit="return checkfields()">
<table>
<tr>
<td> Your name*:</td>
<td> <input name="name" size="30" maxlength="45"> </td>
</tr>
<tr>
<td>Your email*:</td>
<td><input name="email" size="30" maxlength="45"></td>
</tr>
<tr>
<td colspan="2"><p align="center">Enter your friend's email addresses:</p>
</td>
</tr>
<tr>
<td>Email 1*:</td>
<td><input name="fmail1" class="bordesolid1" size="30" maxlength="50"></td>
</tr>
<tr>
<td>Email 2*:</td>
<td><input name="fmail2" size="30" maxlength="50"></td>
</tr>
<tr>
<td>Email 3*:</td>
<td><input name="fmail3" size="30" maxlength="50"></td>
</tr>
<tr>
<td colspan="2"><p align="center"><span>This message will contain your name & email address.</span>
<br>
<input onClick="validate();" type="button" value="click once to send">
<input type=hidden name=refurl value="<? print $refurl;?>">
</td>
</tr>
</table>
</form>
</td>
</tr>
</table>
PHP Code:
<?php
if(count($_POST)) {
foreach(array('fmail1','fmail2','fmail3','email','name') as $key) $_POST[$key] = strip_tags($_POST[$key]);
if(!is_secure($_POST)) {
die("Peace People! Stop Spamming!");
}
$name = $_POST[name];
$email = $_POST[email];
$fmail1 = $_POST[fmail1];
$fmail2 = $_POST[fmail2];
$fmail3 = $_POST[fmail3];
$refurl = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$to = "arvindsri123#yahoo.com";
$subject = "Recommendation form submission";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: '.$email."\r\n";
$headers .= 'Reply-To: '.$email."\r\n".
'X-Mailer: PHP/' . phpversion();
$message = '<html><body>';
$message.='<p style="margin-top:10px;">'.$name.' has used your recommendation form using an email address of '.$email.' </p>';
$message.='<p style="margin-top:10px;">The people the recommendation has been submitted to are: </p>';
$message.='<p style="margin-top:10px;">'.$fmail1.' </p>';
$message.='<p style="margin-top:10px;">'.$fmail2.' </p>';
$message.='<p style="margin-top:10px;">'.$fmail3.' </p>';
$message.='<p style="margin-top:10px;">The page recommended:</p>';
$message.='<p style="margin-top:10px;">'.$refurl.'</p>';
$message .= '</body></html>';
$sentmail = mail($to, $subject, $message, $headers);
// $thankyoupage = "thankyou.htm";
//echo $sentmail;
if($sentmail) {
$name = $_POST[name];
$email = $_POST[email];
$fmail1 = $_POST[fmail1];
$fmail2 = $_POST[fmail2];
$fmail3 = $_POST[fmail3];
$refurl = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$tsubject = "A web page recommendation from $_POST[name]";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: '.$email."\r\n";
$headers .= 'Reply-To: '.$email."\r\n".
'X-Mailer: PHP/' . phpversion();
$message = '<html><body>';
$message.='<p style="margin-top:10px;">Hi, '.$name.' whose email address is $_POST[email] thought you may be interested in this web page. '.$email.' </p>';
$message.='<p style="margin-top:10px;">'.$refurl.'</p>';
$message .= '</body></html>';
$sentmail = mail($fmail1,$fmail2,$fmail3, $tsubject $message, $headers);
echo '<h4>You have sent emails...</h4>';
//header("Location: $thankyoupage");
exit;
}
function is_secure($ar) {
$reg = "/(Content-Type|Bcc|MIME-Version|Content-Transfer-Encoding)/i";
if(!is_array($ar)) {
return preg_match($reg,$ar);
}
$incoming = array_values_recursive($ar);
foreach($incoming as $k=>$v) if(preg_match($reg,$v)) return false;
return true;
}
function array_values_recursive($array) {
$arrayValues = array();
foreach ($array as $key=>$value) {
if (is_scalar($value) || is_resource($value)) {
$arrayValues[] = $value;
$arrayValues[] = $key;
}
elseif (is_array($value)) {
$arrayValues[] = $key;
$arrayValues = array_merge($arrayValues, array_values_recursive($value));
}
}
return $arrayValues;
}
?>
I am using Bluehost web hosting, and other emails properly working as I said Contact us, Registration confirmation emails.. etc.
Thanks!
If you are running on localhost then it won't send email.. to do so you need to host on server
Try to host on free hosting server.. it will work!

Php form upload and email

I have the following code, ideally, it is expected that the user shall upload a file(image/video) when submitting the form, but it is not compulsory though.
<?php
$to = "someone#example.com";
$fromEmail = $_POST['fieldFormEmail'];
$fromName = $_POST['fieldFormName'];
$subject = $_POST['fieldSubject'];
$message = $_POST['fieldDescription'];
/* GET File Variables */
$tmpName = $_FILES['attachment']['tmp_name'];
$fileType = $_FILES['attachment']['type'];
$fileName = $_FILES['attachment']['name'];
/* Start of headers */
$headers = "From: $fromName";
if (file($tmpName)) {
/* Reading file ('rb' = read binary) */
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
/* a boundary string */
$randomVal = md5(time());
$mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
/* Header for File Attachment */
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n" ;
$headers .= " boundary=\"{$mimeBoundary}\"";
/* Multipart Boundary above message */
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mimeBoundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
/* Encoding file data */
$data = chunk_split(base64_encode($data));
/* Adding attchment-file to message*/
$message .= "--{$mimeBoundary}\n" .
"Content-Type: {$fileType};\n" .
" name=\"{$fileName}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mimeBoundary}--\n";
}
$flgchk = mail ("$to", "$subject", "$message", "$headers");
if($flgchk){
echo "A email has been sent to: $to";
}
else{
echo "Error in Email sending";
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Email Attachment Without Upload - Excellent Web World</title>
<style>
body{ font-family:Arial, Helvetica, sans-serif; font-size:13px;}
th{ background:#999999; text-align:right; vertical-align:top;}
input{ width:181px;}
</style>
</head>
<body>
<form action="Contact.php" method="post" name="mainform" enctype="multipart/form-data">
<table width="500" border="0" cellpadding="5" cellspacing="5">
<tr>
<th>Your Name</th>
<td><input name="fieldFormName" type="text"></td>
</tr>
<tr>
<tr>
<th>Your Email</th>
<td><input name="fieldFormEmail" type="text"></td>
</tr>
<tr>
<th>Subject</th>
<td><input name="fieldSubject" type="text" id="fieldSubject"></td>
</tr>
<tr>
<th>Comments</th>
<td><textarea name="fieldDescription" cols="20" rows="4" id="fieldDescription"></textarea></td>
</tr>
<tr>
<th>Attach Your File</th>
<td><input name="attachment" type="file"></td>
</tr>
<tr>
<td colspan="2" style="text-align:center;"><input type="submit" name="Submit" value="Send"><input type="reset" name="Reset" value="Reset"></td>
</tr>
</table>
</form>
</body>
<html>
The problem that i am facing is,
it runs on page load, and
if file has not been uploaded, it throws a warning.
I tried putting the file upload part under "if filename exists" condition, but then the email does not send the attachment
Please help.
This file name is Contact.php
it runs on page load
enclose mail send feature in
if(isset($_POST['Submit']) && ($_POST['Submit']) == 'Send' )
{
/* process only when submit button whose name='Submit'
and value= 'Send' is pressed
entire PHP code */
}
if file has not been uploaded, it throws a warning.
check before attaching it in PHP
if((empty($_POST['attachment'])) || (empty($_FILES['attachment']))){
//file is not attached, show error
}else{
//file is attached, process it and send via mail
}

PHP Form - not receiving email

I'm not understanding why Im not receiving email from the form after filling out the simple form. After clicking the submit button it redirected to the thank you page with no problem, but no email.
HTML
<form class="action" name="form1" method="POST" action="_sendmail2.php" onSubmit="return CheckAll(this);">
<label class="nick-2">Full Name:</label><br>
<input type="text" class="name" name="full_name">
<label class="nick">Email Address:</label><br>
<input type="text" class="email" name="email"><br>
<div class="radio-toolbar">
<input type="radio" id="radio1" name="agent_type" value="Buyer" checked>
<label for="radio1">Buyer</label>
<input type="radio" id="radio2" name="agent_type" value="Seller">
<label for="radio2">Seller</label>
<input type="radio" id="radio3" name="agent_type" value="Investor">
<label for="radio3">Investor</label>
</div><br>
<input type="submit" class="btn" value="SUBMIT" name="Submit">
</form>
PHP (
<?php
$to = "cluneborg#hotmail.com";
$subject = "New Agent Inquries";
$full_name = $_POST['full_name'];
$email = $_POST['email'];
$agent_type = $_POST['agent_type'];
if($_SERVER['REQUEST_METHOD']=="POST") {
$full_name=str_replace ( array("\n"), array("<br>"),trim($_REQUEST['full_name']));
$email=str_replace ( array("\n"), array("<br>"),trim($_REQUEST['email']));
$agent_type=str_replace ( array("\n"), array(" <br>"),trim($_REQUEST['agent_type']));
$contentmsg=stripslashes("<br><b><font style=color:#CC3300>$subject</font></b><br>
<table width=708 border=0 cellpadding=2 cellspacing=1 bgcolor=#CCCCCC>
<tr>
<td width=165 align=right valign=top bgcolor=#FFFFFF><B>Full Name: </b> </td>
<td width=565 align=left valign=top bgcolor=#FFFFFF> $full_name</td>
</tr>
<tr>
<td width=165 align=right valign=top bgcolor=#FFFFFF><B>Email Address: </b> </td>
<td width=565 align=left valign=top bgcolor=#FFFFFF> $email</td>
</tr>
<tr>
<td width=165 align=right valign=top bgcolor=#FFFFFF><B>Type of Agent:</b> </td>
<td width=565 align=left valign=top bgcolor=#FFFFFF> $agent_type</td>
</tr>
</table>
");
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= 'To: Eric <eluneborg#gmail.com>' . "\r\n";
$headers .= 'From: Texas Real Estate Agent Website' . "\r\n";
if(mail($to,$subject,$contentmsg,$headers)){
header("Location: http://www.magnixsolutions.com/clients/tas/thanks.html");
}
else
{
echo "Mail was not sent!";
}
}
?>
Sometimes it sends email to my hotmail and most of time it get this (checked on cpanel)
This message was created automatically by mail delivery software.
A message that you sent could not be delivered to one or more of its
recipients. This is a permanent error. The following address(es) failed:
cluneborg#hotmail.com
Domain magnixsolutions.com has exceeded the max defers and failures per hour (5/5 (55%)) allowed. Message discarded.
(Tested) - There were a few issues with your code.
The most important thing, is the # symbol in #mail - This will not execute, it needs to be removed.
Now, this line: (in PHP)
$_REQUEST['type_agent']
should be:
$_REQUEST['agent_type']
as per: (in HTML form)
<input type="radio" id="radio3" name="agent_type" value="Investor">
Then your headers were incorrect, where I added a few \r\n
One of your headers (in PHP)
$headers .= "From: ".$from."";
has been changed to:
$headers .= "From: $full_name <$email>\r\n";
Sidenote: It could be replaced with
$headers .= "From: $fromemail <$email>\r\n";
if you want the name to appear as "New Agent" in mail, instead of the person's name sending the Email.
Using this $fromemail="New Agent"; in conjunction with $from=$fromemail; and $headers .= "From: ".$from."";
would have resulted in mail going to SPAM, being it's not an actual Email address.
Plus, upon testing your original code, it did not come in as proper HTML, but the codes themselves showed up in the Email; that has been corrected.
If you want the Email and the name, you need to use two different variables.
I.e.:
$headers .= 'From: YourName <YourName#domain.com>' . "\r\n";
and in your case:
$headers .= "From: $full_name <$email>\r\n";
Rewrite: (PHP)
<?php ob_start();
// commented out - is not needed for the time being
// $fromemail="New Agent"; // change here if you want
$toemail="email#example.com"; // change here if you want
$sub="Agent Inquiries"; // change here if you want
$success_page_name="thanks.html";
////// do not change in following
if($_SERVER['REQUEST_METHOD']=="POST")
{
$full_name=str_replace ( array("\n"), array("<br>"),trim($_REQUEST['full_name']));
$email=str_replace ( array("\n"), array("<br>"),trim($_REQUEST['email']));
$type_agent=str_replace ( array("\n"), array("<br>"),trim($_REQUEST['agent_type']));
$contentmsg=stripslashes("<br><b><font style=color:#CC3300>$sub</font></b><br>
<table width=708 border=0 cellpadding=2 cellspacing=1 bgcolor=#CCCCCC>
<tr>
<td width=165 align=right valign=top bgcolor=#FFFFFF><B>Full Name: </b> </td>
<td width=565 align=left valign=top bgcolor=#FFFFFF>$full_name</td>
</tr>
<tr>
<td width=165 align=right valign=top bgcolor=#FFFFFF><B>Email Address: </b> </td>
<td width=565 align=left valign=top bgcolor=#FFFFFF>$email</td>
</tr>
<tr>
<td width=165 align=right valign=top bgcolor=#FFFFFF><B>Type of Agent:</b> </td>
<td width=565 align=left valign=top bgcolor=#FFFFFF>$type_agent</td>
</tr>
</table>
");
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= "From: $full_name <$email>\r\n";
#mail($toemail,$sub,$contentmsg,$headers);
header("Location:$success_page_name");
}
?>
Footnotes:
Including the # symbol in #mail suppresses errors and does not execute the function, so you will want to remove it..
In my testing, I removed onSubmit="return CheckAll(this); since your full code didn't include that function. Should it fail, then you may need to remove it also.
Remove the # sign from the #mail command and it might give you a helpful error. The # sign there is suppressing errors:
http://www.php.net/manual/en/language.operators.errorcontrol.php
You need to add EOL character \n in headers to separate. Don't know whether this is the solution, but it is at least one problem that needs attention.
$headers = "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
$from=$fromemail;
$headers .= "From: ".$from."\n";
In addition to the error suppression answers/comments, you can also make sure that mail() returns true indicating your server has accepted it and will attempt delivery.
$success = mail($toemail,$sub,$contentmsg,$headers);
var_dump( $success ); // should be true

PHP Form Email Request Not Bringing form data through

I have been working on a php script and a html form (both in separate files) that takes data from a form and emails it to me. I am having difficulty getting the form data that the user fills out to come through on the email.
I would like for the email to contain the user's email as the From in the email.
Can anyone help me figure out what is wrong with the files?
HTML Form:
<form id="ContactUs" name="ContactUs" method="post" action="sendform/sendform.php">
<table width="60%" border="0" cellpadding="2px" style="position:relative; left:20%">
<tr>
<td width="25%" align="right">Name:</td>
<td width="75%" align="left"><input name="ContactName" type="text" size="40" maxlength="100" /></td>
</tr>
<tr>
<td align="right">Email Address:</td>
<td align="left"><span id="sprytextfield1">
<input name="EmailAddress" type="text" id="EmailAddress" size="40" maxlength="150" />
<span class="textfieldRequiredMsg">A value is required.</span></span></td>
</tr>
<tr>
<td align="right">Phone Number:</td>
<td align="left"><span id="sprytextfield2">
<label for="PhoneNumber"></label>
<input name="PhoneNumber" type="text" id="PhoneNumber" maxlength="15" />
<span class="textfieldRequiredMsg">A value is required.</span></span></td>
</tr>
<tr>
<td align="right">Practice Name:</td>
<td align="left"><input name="PracticeName" type="text" size="40" maxlength="100" /></td>
</tr>
<tr>
<td align="right">Message:</td>
<td align="left"><textarea name="Message" cols="40" rows="10"> </textarea></td>
</tr>
<tr>
<td align="center" width="25%"></td>
<td align="center" width="75%"><input name="SubmitForm" type="submit" id="SubmitForm" onclick="MM_popupMsg('Are you sure you would like to submit this form?\r');return document.MM_returnValue" value="Submit Form" /><input type="reset" name="ResetForm" id="ResetForm" value="Reset Form" /></td>
</table>
</form>
Separate PHP file named sendform.php
<?php
// Where to redirect after form is processed.
$url = 'ThankYou.php';
// multiple recipients
$to = 'T#domain.com';
// subject
$subject = 'Someone sent you a contact request';
$headers = 'From: '.$EmailAddress.'/r/n';
$headers .= 'MIME-Version: 1.0\r\n';
$headers .= 'Content-Type: text/html; charshet=ISO-8859-1\r\n';
// message
$messagetext = '<html><body>';
$messagetext .= ' <p>Website Form Submit</p>';
$messagetext .= ' <table>';
$messagetext .= ' <tr><td align="right">Name:</td><td>'; $_GET[$ContactName] .'</td></tr>';
$messagetext .= ' <tr><td align="right">Email Address:</td><td align="left">'; $EmailAddress .'</td></tr>';
$messagetext .= ' <tr><td align="right">Phone Number:</td><td align="left">'; $PhoneNumber .'</td></tr>';
$messagetext .= ' <tr><td align="right">Practice Name:</td><td align="left">'; $PracticeName .'</td></tr>';
$messagetext .= ' <tr><td align="right">Message:</td><td align="left">'; $Message .'</textarea></td></tr>';
$messagetext .= ' </table></body></html>';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Mail it
mail($to, $subject, $messagetext, $headers);
//echo $message;
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">'
?>
You're using POST in your form but you are not referencing the post variables. Instead of $_GET[$ContactName], use $_POST[$ContactName]. Do this for all POSTed variables.
One step at a time! Forget the email function altogether for now, do things in order.
Make your form, then make sure it's displaying as you expect in the browser.
Then on the processing page (sendform/sendform.php), echo out all the data which would be sent from the form to make sure they're all there, present and ok.
ie
print_r($_POST);
THEN once you are happy with that stage, you can apply the vars in the email function and test the final result, tweaking where required or fixing bugs etc.
At present, however, you're not doing anything with the POSTed data. In sendform.php, you have this:
$headers = 'From: '.$EmailAddress.'/r/n';
However there is no reference to it in that file to set it, or set that variable to POSTed or GET data. As such, it'll be empty.
You should check your error logs too, as this would have shown you this var is empty and lead you to back track to your issue. error logs are a must whenever coding in PHP, even for the pro's.
You also have this:
$messagetext .= '<tr><td align="right">Name:</td>
<td>'; $_GET[$ContactName] .'</td></tr>
';
Your form is set to POST data, not GET.
So your data is stored in PHP's $_POST array. So using your form names, the email address would be:
$_POST['EmailAddress'];
// You can use this, or set it to a variable, ie
$EmailAddress = $_POST['EmailAddress'];
Important note:
You really want to validate people's inputs before emailing, or you could open yourself up to be a spammers delight. Such as strlen() to match your form maxlengths, is_numeric(), and regex to check their inputted data is not some Javascript or whatever trying to send thousands of emails through your site (it happens!).
Using them all in conjunction with each other where appropriate, you ensure users can only enter data you allow and you stop any bad things coming through.
Send them back to the form with an error message if there is anything wrong, do this until you're happy the data is acceptable to send through your server's mail system and then allow it.
People using your badly written code to spam the world wont just be an annoyance to you having to resolve that. You could end up having your domain name where the form is hosted blacklisted as a spammy site - not good.
Here is a tested version with the From: now showing in the appropriate location of the Email.
Quick note: There was two seperate header bodies which broke up your code.
One under $subject and the other over $messagetext. All are inside one body of headers now.
Plus, you had $headers = 'From: '.$EmailAddress.'/r/n'; which is invalid.
This should have read as $headers = 'From: '.$EmailAddress.'\r\n'; with \ instead of /.
More on the mail() function can be read by visiting PHP.net on mail() - here.
Working code
<?php
$url = 'ThankYou.php';
$ContactName = $_POST['ContactName'];
$EmailAddress = $_POST['EmailAddress'];
$PhoneNumber = $_POST['PhoneNumber'];
$Message = $_POST['Message'];
$PracticeName = $_POST['PracticeName'];
$to = "email#example.com";
$subject = 'Someone sent you a contact request';
// message
$messagetext = '<html><body>';
$messagetext .= ' <p>Website Form Submit</p>';
$messagetext .= ' <table>';
$messagetext .= ' <tr><td align="right">Name:</td><td>'.$ContactName.'</td></tr>';
$messagetext .= ' <tr><td align="right">Email Address:</td><td align="left">'.$EmailAddress.'</td></tr>';
$messagetext .= ' <tr><td align="right">Phone Number:</td><td align="left">'.$PhoneNumber.'</td></tr>';
$messagetext .= ' <tr><td align="right">Practice Name:</td><td align="left">'.$PracticeName.'</td></tr>';
$messagetext .= ' <tr><td align="right">Message:</td><td align="left">'.$Message.'</textarea></td></tr>';
$messagetext .= ' </table></body></html>';
// To send HTML mail, the Content-type header must be set
$headers = "MIME-Version: 1.0\n";
$headers .= "Content-Type: text/html; charset=iso-8859-1\n";
$headers .= "From: $EmailAddress" . "\r\n" .
"Reply-To: $EmailAddress" . "\r\n" .
'X-Mailer: PHP/' . phpversion();
// Mail it
mail($to, $subject, $messagetext, $headers);
//echo $message;
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
//echo "Success"; // my testing method
?>
Additional options:
To make sure someone fills in all the fields and not send mail unless they do, then you can use the following and make sure you remove the in your <textarea name="Message"... because that is considered as input.
if(!empty($_POST['EmailAddress']) && (!empty($_POST['ContactName']))
&& (!empty($_POST['PhoneNumber']))
&& (!empty($_POST['PracticeName']))
&& (!empty($_POST['Message']))
)
{
mail($to, $subject, $messagetext, $headers);
//echo $message;
// echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
echo "Success";
}
else {
echo "Mail failed. All fields must be filled.";
}
There are more improvements that can be done, for instance Email validation such as FILTER_VALIDATE_EMAIL.
Example:
$email = $_POST['EmailAddress'];
if(empty($_POST['EmailAddress']) || !filter_var($EmailAddress, FILTER_VALIDATE_EMAIL)) {
die("Please enter a valid email");
}
More on FILTER_VALIDATE_EMAIL can be found on the PHP.net Website
http://php.net/manual/en/filter.filters.validate.php
I have fixed your code. Enter the email in $to variable whom you want to send the email.
<?php
$ContactName = $_POST['ContactName'];
$EmailAddress = $_POST['EmailAddress'];
$PhoneNumber = $_POST['PhoneNumber'];
$Message = $_POST['Message'];
$PracticeName = $_POST['PracticeName'];
$to = 'ENTER EMAIL ADDRESS ON WHICH YOU WANT TO SEND EMAIL';
$subject = 'Someone sent you a contact request';
$headers = 'From: '.$EmailAddress.'/r/n';
$headers .= 'MIME-Version: 1.0\r\n';
$headers .= 'Content-Type: text/html; charshet=ISO-8859-1\r\n';
// message
$messagetext = '<html><body>';
$messagetext .= ' <p>Website Form Submit</p>';
$messagetext .= ' <table>';
$messagetext .= ' <tr><td align="right">Name:</td><td>'.$ContactName.'</td></tr>';
$messagetext .= ' <tr><td align="right">Email Address:</td><td align="left">'.$EmailAddress.'</td></tr>';
$messagetext .= ' <tr><td align="right">Phone Number:</td><td align="left">'.$PhoneNumber.'</td></tr>';
$messagetext .= ' <tr><td align="right">Practice Name:</td><td align="left">'.$PracticeName.'</td></tr>';
$messagetext .= ' <tr><td align="right">Message:</td><td align="left">'.$Message.'</textarea></td></tr>';
$messagetext .= ' </table></body></html>';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1'."\r\n";
// Mail it
mail($to, $subject, $messagetext, $headers);
//echo $message;
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';

Foreach loop not working in PHP when formatted for mail()

I have a array of objects and wants to create an online invoice to be sent on mail . For this I have modified the message as below :
function mail_invoice($buyer_info,$items_info ,$date,$final_amount)
{
global $template;
//var_dump($buyer_info);
$to = $buyer_info->email;
$from_mail = 'info#7sisters.in';
//echo $msg.$to.$from;sender_mail
$subject = "Your Invoice";
$message = "Your Shopping Details";
$message .= '
<h2>RETAIL INVOICE</h2>
<p>
SRI SAI VENTURES PVT LTD.<br />
House Number 13A<br />
Nizarapar<br />
Guwahati - 781003<br />
Assam
</p>
<p>
Buyer <br />
<b>'.$buyer_info->fname.' '.$buyer_info->lname.'</b><br />
'.$buyer_info->address.'<br />
PIN - '.$buyer_info->pin.'<br />
PHONE '.$buyer_info->phone.'<br />
</p>
<p>
Dispatch Date : '.$date.'
</p>
<table>
<tr>
<th>Sl No</th>
<th>Description of goods</th>
<th>Quantity</th>
<th>Rate</th>
<th>Amount</th>
</tr>'.
(foreach $items_info as $a=>$v).' <----line no 1025
<tr>
<td>'.++$ind.'</td>
<td>'.$v->brand.','.$v->model.'</td>
<td>'.$v->quantity.'</td>
<td>'.$v->price.'</td>
<td>'.$v->total_cost.'</td>
</tr>'.
{/foreach}
.'<tr>
<td> </td>
<td> </td>
<td> </td>
<td>Total Cost </td>
<td>'.$final_amount.'</td>
</tr>
</table>
';
$from = $from_mail;
//$headers = "From:" . $from;
$headers = "From:" . $from . "\r\n" .
"Reply-To:" . $from . "\r\n" .
"X-Mailer: PHP/" . phpversion();
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to,$subject,$message,$headers);
//$template->main_content = $template->fetch(TEMPLATE_DIR . 'messag_sent_to_friend.html');
}
But I am getting error message Parse error: syntax error, unexpected T_FOREACH in C:\wamp\www\eshop\class\base\user.base.class.php on line 1025 . Whats wrong I am doing? Or I can't use foreach there . Please help
You cannot nest a foreach statement in string concatenation. Just split it:
....
<th>Amount</th>
</tr>';
foreach $items_info as $a=>$v){
$message .= '<tr>
<td>'.++$ind.'</td>
<td>'.$v->brand.','.$v->model.'</td>
<td>'.$v->quantity.'</td>
<td>'.$v->price.'</td>
<td>'.$v->total_cost.'</td>
</tr>';
}
$message .= '<tr>
<td> </td>
<td> </td>
....
foreach ($items_info as $a=>$v){
$message .= ' <tr> <td>........
function mail_invoice($buyer_info,$items_info ,$date,$final_amount)
{
global $template;
//var_dump($buyer_info);
$to = $buyer_info->email;
$from_mail = 'info#7sisters.in';
//echo $msg.$to.$from;sender_mail
$subject = "Your Invoice";
$message = "Your Shopping Details";
$message .= '
<h2>RETAIL INVOICE</h2>
<p>
SRI SAI VENTURES PVT LTD.<br />
House Number 13A<br />
Nizarapar<br />
Guwahati - 781003<br />
Assam
</p>
<p>
Buyer <br />
<b>'.$buyer_info->fname.' '.$buyer_info->lname.'</b><br />
'.$buyer_info->address.'<br />
PIN - '.$buyer_info->pin.'<br />
PHONE '.$buyer_info->phone.'<br />
</p>
<p>
Dispatch Date : '.$date.'
</p>
<table>
<tr>
<th>Sl No</th>
<th>Description of goods</th>
<th>Quantity</th>
<th>Rate</th>
<th>Amount</th>
</tr>';
foreach ($items_info as $v){
$message .= '<tr>
<td>'.++$ind.'</td>
<td>'.$v->brand.','.$v->model.'</td>
<td>'.$v->quantity.'</td>
<td>'.$v->price.'</td>
<td>'.$v->total_cost.'</td>
</tr>';
}
$message .= '<tr>
<td> </td>
<td> </td>
<td> </td>
<td>Total Cost </td>
<td>'.$final_amount.'</td>
</tr>
</table>';
$from = $from_mail;
//$headers = "From:" . $from;
$headers = "From:" . $from . "\r\n" .
"Reply-To:" . $from . "\r\n" .
"X-Mailer: PHP/" . phpversion();
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to,$subject,$message,$headers);
//$template->main_content = $template->fetch(TEMPLATE_DIR . 'messag_sent_to_friend.html');
}

Categories