PHP mailer not working for attachments? - php

I am stucked while giving file upload path, i have a html file input name uploadfile and i am using phpmailer() to send attachement. Please help me i need php developers support. here is my code tell me why i am getting Could not access file error. and my email is not having attachment only message is coming.
<div class="field">
<label for="Browse">File to upload: <span class="required">*</span></label>
<div class="inputs">
<input name="uploadedfile" id="uploadedfile" type="file" style=" height: 37px;" name="MAX_FILE_SIZE" value="100000" />
</div>
</div>
//Form Fields
$name = $_POST["name"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$subject = $_POST["subject"];
$message = $_POST["message"];
$verify = isset($_POST["verify"]) ? $_POST["verify"] : "";
$path = $_FILES["uploadedfile"]["name"];
echo $path;
$encoding = 'base64';
$type = 'application/octet-stream';
$objmail->From = $email;
$objmail->FromName = $name;
$objmail->AddAddress($toAddress, $toName);
$objmail->AddReplyTo($email, $name);
$objmail->Subject = $email_subject;
$objmail->MsgHTML($email_body);
$objmail->AddAttachment($path,$encoding,$type);
if(!$objmail->Send()) {
$error = "Message sending error: ".$objmail->ErrorInfo;
}
}

Two problems:
First:
$path = $_FILES["uploadedfile"]["name"];
$objmail->AddAttachment($path,$encoding,$type);
$path is going to be the name of the file as it was on the CLIENT machine. That has absolutely nothing to do with the temporary file that PHP stores it in, which is listed in ['tmp_name'].
Second:
You don't validate that an upload occurred at all, and are simply assuming it succeeded. At minimum, you need to have
if ($_FILES['uploadedfile']['error'] === UPLOAD_ERR_OK) {
$objmail->AddAttachment(
$_FILES['uploadedfile']['tmp_name'], // temp location on server
$_FILES['uploadedfile']['name'], // name that appears in email
'base64',
$_FILES['uploadedfile']['type'] // mime type provided by uploader
);
}

Related

HTML form with PHP does not send from my website to my Gmail account [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 15 days ago.
I have made a regular HTML form with POST method and action referring to a PHP page with a code I found here on Stackoverflow. Also, I have added a javascript validation.
I have checked everything and to my knowledge, everything is fine. Yet, I never receive the email. At first, I thought it was the javascript intervening with the $_POST['submit'] but even without the validation, the form doesn't send me the data. Furthermore, the PHP has an echo line which doesn't show either when trying to submit the form without the validation. I have googled that this might have something to do with the code being outdated as it uses a direct mail() instruction. Still, I would like to send the form to a specific email. Is there a way to do it? Can you help me with the right code?
I even tried using direct HTML mailto: attribute but not even that worked.
Finally, I tried using some SMTP server code I found in other questions here but I can't seem to figure it out. On the server side (Gmail), I allowed POP3 and IMAP in my Gmail account.
I know there are similar questions out there but none of the answers work for me. As I am a noob, I would appreciate the simplest solution involving only PHP coding or Gmail setting. I don't wish to install or incorporate any third-party stuff.
Thanks in advance.
This is what I have tried:
HTML:
<form method="post" action="send.php" id="qForm" enctype="multipart/form-data" onsubmit="validateCaptcha()" >
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="message">Your message:</label>
<textarea id="message" maxlength="500" type="text" name="message" required
placeholder="Write your message here."></textarea>
<div id="captcha"></div>
<input type="text" placeholder="Copy the code here." id="cpatchaTextBox"/>
<input type="submit" value="SEND" name="submit" id="submit" >
</form>
PHP (send.php):
<?php
if(isset($_POST['submit'])){
$to = "myname#gmail.com"; // this is my Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$subject = "Web message";
$message = $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$headers,$message);
mail($from,$subject,$headers2,$message); // sends a copy of the message to the sender
echo "Message sent. " . "\n\n" . " Thank you, " . $name . ", we will be in touch.";
}
?>
The extra SMTP code I found here:
<?php
$mail->Mailer = "smtp";
$mail->Host = "ssl://smtp.gmail.com";
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->Username = "myname#gmail.com";
$mail->Password = "mypassword123";
?>
JAVASCRIPT validation:
var code;
function createCaptcha() {
//clear the contents of captcha div first
document.getElementById('captcha').innerHTML = "";
var charsArray =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ#!#$%^&*";
var lengthOtp = 6;
var captcha = [];
for (var i = 0; i < lengthOtp; i++) {
//below code will not allow Repetition of Characters
var index = Math.floor(Math.random() * charsArray.length + 1); //get the next character from the array
if (captcha.indexOf(charsArray[index]) == -1)
captcha.push(charsArray[index]);
else i--;
}
var canv = document.createElement("canvas");
canv.id = "captcha";
canv.width = 100;
canv.height = 50;
var ctx = canv.getContext("2d");
ctx.font = "25px Georgia";
ctx.strokeText(captcha.join(""), 0, 30);
//storing captcha so that can validate you can save it somewhere else according to your specific requirements
code = captcha.join("");
document.getElementById("captcha").appendChild(canv); // adds the canvas to the body element
}
function validateCaptcha() {
event.preventDefault();
debugger
if (document.getElementById("cpatchaTextBox").value == code) {
alert("Thank you for your message. We will be in touch.");
window.location.reload();
}else{
alert("Sorry. Try it again.");
createCaptcha();
}
}
When the form starts to submit you run validateCaptcha.
The first thing you do is call event.preventDefault which prevents the form from submitting.
Later you call window.location.reload which reloads the page, using a GET request, so $_POST['submit']) is not set.
If you want the data to submit, don't cancel the action.

PHP send form to email - display content on next page

I'm having some issues with getting the form content sent to email and saved to a session and then displayed on next page.
I have form on contact.shtml which action takes it to mail.php and when content are sent goes to thank_you.shtml.
I need the content shown on the thank_you -page.
All my pages are *.shtml - are this an disadvantage for this?
Codesnippets:
mail.php
$name = $_POST['name'];
$_SESSION['name'] = $name;
$email = $_POST['email'];
$_SESSION['email'] = $email;
$phone = $_POST['phone'];
$_SESSION['phone'] = $phone;
thank_you:
<?php
echo "Navn:" . "$_SESSION['name']";
echo "Email:" . "$_SESSION['email']";
echo "Telefon:" . "$_SESSION['phone']";
?>
I have the obvious on page thank_you and mail.php.
<?php
session_start();
?>
Beside these few lines i have several more with text input and also image files for which i want to show the filename and extensions and also a small preview.
Am i missing something or on the complete wrong track?
You could bypass using a session. While I like separation of concerns the following outline 'all-in-one' solution would satisfy your problem:
<?php
$email = null;
$sent = false;
$error = null;
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = isset($_POST['email']) ? $_POST['email'] : null;
if($email && filter_var($email, FILTER_VALIDATE_EMAIL)) {
// supplied email looks good, send email here.
$sent = true;
} else {
$error = 'Please enter a valid email address.';
}
}
?>
html goes here..
<?php if($sent) {
echo 'Thankyou. The email you supplied is: ' . htmlspecialchars($email);
?>
<?php } else { ?>
<?php echo $error ? '<p>' . $error . '</p>' : ''; ?>
<form method="POST">
Email:
<input type="text" name="email" value="<?php echo htmlspecialchars($email) ?>">
<input type="submit">
</form>
<?php } ?>
If a valid email is posted, you can then trigger your mail out.
Do you really need to display the gathered user data?
<?php
echo "Navn:" . htmlentities($_SESSION['name']);
echo "Email:" . htmlentities($_SESSION['email']);
echo "Telefon:" . htmlentities($_SESSION['phone']);
?>
You have to remove the quotes around the variables. Use htmlentities to convert all applicable characters to HTML entities

after clicking submit on a contact form, how do i stay on the same page in wordpress?

So I created a custom contact form in WordPress, using PHP. The form sends, and I am receiving emails. The problem I'm having is that once you hit submit, it goes to a post page, and doesn't stay on the original page.
I've tried using a session and header location (didn't work)
I also tried putting this in my action"<?php echo $_SERVER['PHP_SELF']; ?>", doesn't work either. (mail just doesn't send it and sends me to 404 page.
So I'm a little stuck, as to fix this problem. Normally I would have no problems if this was a static web page, but because I'm using WordPress, this task seems to be more troublesome.
Here is a link to the website http://www.indianpointresort.ca/
Here is the php validation:
<?php
/*session_start();
if(!isset($_SESSION['afaisfjisjfijfjiwaefjawsefijef'])){
$url = 'http://www.indianpointresort.ca/';
header("Location:home.php?url=$url");
}*/
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$phone = trim($_POST['phone']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
echo "$name | $email | $phone | $subject | $message";
if(isset($_POST['submit'])){
$boolValidationOK = 1;
$strValidationMessage = "";
//validate first name
//validate last name
if(strlen($name)<3){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill in a proper first and last name </br>";
}
//email validation:
$emailValidate = validate_email( $email );// calls the function below to validate the email addy
if(!$emailValidate ){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill in proper email address </br>";
}
//validate phone
$phone = checkPhoneNumber($phone);
if(!$phone){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill proper phone number </br>";
}
//validate subject
if(strlen($subject)<3){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill in a proper subject description </br>";
}
//validate description
if(strlen($message)<3){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill in a proper message </br>";
}
if($boolValidationOK == 1){
//$strValidationMessage = "SUCCESS";
//MAIL SECURITY !!!!!!!
// WE MUST VALIDATE AGAINST EMAIL INJECTIONS; THE SPAMMERS BEST WEAPON
$badStrings = array("Content-Type:",
"MIME-Version:",
"Content-Transfer-Encoding:",
"bcc:",
"cc:");
foreach($_POST as $k => $v){// change to $_POST if your form was method="post"
foreach($badStrings as $v2){
if(strpos($v, $v2) !== false){
// In case of spam, all actions taken here
//header("HTTP/1.0 403 Forbidden");
echo "<script>document.location =\"http://www.bermuda-triangle.org/\" </script>";
exit; // stop all further PHP scripting, so mail will not be sent.
}
}
}
$ip = $_SERVER['REMOTE_ADDR'];
//echo $ip;
/* Spammer List: IP's that have spammed you before ***********/
$spams = array (
"static.16.86.46.78.clients.your-server.de",
"87.101.244.8",
"144.229.34.5",
"89.248.168.70",
"reserve.cableplus.com.cn",
"94.102.60.182",
"194.8.75.145",
"194.8.75.50",
"194.8.75.62",
"194.170.32.252"
//"S0106004005289027.ed.shawcable.net" Phil's IP as test
); // array of evil spammers
foreach ($spams as $site) {// Redirect known spammers
$pattern = "/$site/i";
if (preg_match ($pattern, $ip)) {
// whatever you want to do for the spammer
echo "logging spam activity..";
exit();
}
}
$to = "";
//$subject = " Indian Point";
// compose headers
$headers = "From: Indian Point Resort.\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "X-Mailer: PHP/".phpversion();
$message = wordwrap($message, 70);
// send email
mail($to, $subject, $message, $headers);
}
}//end of submit
//validate phone number
function checkPhoneNumber($number){
$number = str_replace("-", "", $number);
$number = str_replace(".", "", $number);
$number = str_replace(" ", "", $number);
$number = str_replace(",", "", $number);
$number = str_replace("(", "", $number);
$number = str_replace(")", "", $number);
if((strlen($number) != 10) || (!is_numeric($number))){
return false;
}else{
return $number;
}
}
//email validation
function validate_email( $senderemail ){ // this is a function; it receives info and returns a value.
$email = trim( $senderemail ); # removes whitespace
if(!empty($email) ):
// validate email address syntax
if( preg_match('/^[a-z0-9\_\.]+#[a-z0-9\-]+\.[a-z]+\.?[a-z]{1,4}$/i', $email, $match) ):
return strtolower($match[0]); # valid!
endif;
endif;
return false; # NOT valid!
}
?>
Here is the form:
<div id="msgForm" class=" msgForm five columns">
<h4>Questions?</h4>
<h5>Send us a message!</h5>
<form id="contactForm" name="contactForm" method="post" action="<?php the_permalink(); ?>">
<p><input type="text" name="name" value="<?php echo $name; ?>" placeholder="name*"/></p>
<p><input type="email" name="email" placeholder="E-mail*"/></p>
<p><input type="text" name="phone" placeholder="Phone #*"/></p>
<p><input type="text" name="subject" placeholder="subject*"/></p>
<p><textarea name="message" placeholder="Message*"></textarea></p>
<p><input type="submit" name="submit" placeholder="Submit"/></p>
<div class="error">
<?php
if($strValidationMessage){
echo $strValidationMessage;
}
?>
</div>
</form>
</div><!--end of form-->
Well, to start off I would remove that gmail account from your info (just to be safe).
Secondly I would advise you to use the sendmail scripts provided by Wordpress.
There are plugins like gravityforms which allow you to make a form and decide all these options without making a static form, nor a new template file for that matter.
You can only change to which page the form will redirect after the refresh (the action will decide that)
If you want it to stay on the same page you can put the page itself in the action and on top put an if statement like
if(isset($_POST['submit'])){
//validation, sendmail, and possibly errors here
}
else{
//show the form
}
anyway, a refreshing webform is as standard as it gets. It's just how it submits things. The only way you could prevent a page is by using jquery or javascript like so: (give your submit an id)
$('#submit').on("click", function(e){
//this prevents any submit functionality (like refresh)
e.preventDefault();
//custom code to get values here and put them in the sendmail function like so:
var message = $('$message').text();
}
Try ajax form submission. And add the insert query in a separate file.

PHP Mailer Doesn't Send All Fields

I am new to PHP and I am trying to create a PHP form field and I have four "Check Boxes" named Output1, Output2, Output3, and Output4 but when I select all four Check Boxes it only send me one and not all four values.
NOTE I have other fields on this from as well but I just wanted to provide you the HTML form info for Output.
Here is the HTML:
<form id="surveyForm" class="form" action="mailsurvey.php" method="post" name="surveyForm" enctype="multipart/form-data" onsubmit="return ValidateContactForm2();">
<input id="Output1" type="checkbox" name="Output1" value="Isolated" />
<input id="Output2" type="checkbox" name="Output2" value="Isolated" />
<input id="Output3" type="checkbox" name="Output3" value="Isolated" />
<input id="Output4" type="checkbox" name="Output4" value="Isolated" />
</form>
PHP Code:
<?php
require("includes/class.phpmailer.php");
require("includes/class.smtp.php");
require("includes/class.pop3.php");
if($_FILES['headshot']['name']!="")
{
$imgtype=explode('.',$_FILES['headshot']['name']);
$len=sizeof($imgtype);
$image_file=uniqid().'.'.$imgtype[$len-1];
$tmppath='uploads/';
move_uploaded_file($_FILES['headshot']['tmp_name'],$tmppath.$image_file);
$file_path=$tmppath.$image_file;
}
else
{
$file_path="";
}
if($_FILES['bodyshot']['name']!="")
{
$imgtype=explode('.',$_FILES['bodyshot']['name']);
$len=sizeof($imgtype);
$image_file=uniqid().'.'.$imgtype[$len-1];
$tmppath='uploads2/';
move_uploaded_file($_FILES['bodyshot']['tmp_name'],$tmppath.$image_file);
$file_path2=$tmppath.$image_file;
}
else
{
$file_path2="";
}
$mail = new PHPMailer();
$mail->Host = "localhost";
$mail->Mailer = "smtp";
$name = $_POST['name'];
$company = $_POST['company'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['Comments'];
$totalpower = $_POST['Total_Power']." ".$_POST['Total_Power2']." ".$_POST['Total_Power3']." ".$_POST['Total_Power4']." ".$_POST['Total_Power5'];
$input = $_POST['Input']." ".$_POST['Input2']." ".$_POST['Input3']." ".$_POST['Input4'];
$strings = $_POST['Strings4']." ".$_POST['Strings3']." ".$_POST['Strings2']." ".$_POST['Strings'];
$output = $_POST['Output1']." ".$_POST['Output2']." ".$_POST['Output3']." ".$_POST['Output4'];
$dimming = $_POST['Dimming4']." ".$_POST['Dimming3']." ".$_POST['Dimming2']." ".$_POST['Dimming'];
$packaging = $_POST['Packaging4']." ".$_POST['Packaging3']." ".$_POST['Packaging2']." ".$_POST['Packaging'];
$subject = "New Product Inquiry / Survey";
$body = "Name: " .$name. "<br> ".
"Company: " .$company. "<br>".
"Phone: " .$phone."<br>".
"Email: " .$email."<br><br><hr>".
"Total Power: " .$totalpower."<br>".
"Input: " .$input."<br>".
"Strings: " .$strings."<br>".
"Output: " .$output."<br>".
"Dimming: " .$dimming."<br>".
"Packaging: " .$packaging."<br>".
"Comments: " .$comments."<br>"
;
$mail->IsSMTP();
$mail->From = 'support#domain.com';
$mail->FromName = 'support#domain.com';
$mail->Subject = "New Product Inquiry";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
if($file_path!="")
{
$mail->AddAttachment($file_path);
}
if($file_path2!="")
{
$mail->AddAttachment($file_path2);
}
$mail->MsgHTML($body);
$mail->AddAddress('email#domain.com');
if(!$mail->Send())
{
$msg = "Unable to send email";
}
else
{
$msg = header("location: thank-you2.php");
}
?>
Can someone please tell me why this form will not send ALL Output Fields if a user selects all four boxes. If you have any questions please let me know.
Thanks,
Frank
I figured out what my problem was and the reason why I wanted to post this answer for others to be aware of.
My problem was I was working on the wrong PHP file. I have two of the same PHP files in my site one was burred under a couple folders and one was at the root of the site. The one burred was the one I should have been working on making changes to because that was the LIVE file. While I was uploading a file that wasn't working because it was the wrong one. I figured that out by double check the path in the form element of the form page.
<form id="surveyForm" class="form" **action="subfolder/formmailer_scripts/mailsurvey.php"** method="post" name="surveyForm" enctype="multipart/form-data" onsubmit="return ValidateContactForm2();">
So the morel of the story is pay attention and make sure you don't over look the simple things. I wasted about an hour on this reuploading a file that wasn't were it need to be. Hope this helps others!

How can I easily allow users to upload multiple files?

I'm looking for a very easy way to allow users to upload files (html) to my site. I've tried things like plupload and uploadify and they seem to difficult to implement/buggy. Are there any simple solutions out there?
I actually just worked on this issue recently. Ill let you use my code i wrote. What it does is as soon as a user browses for one file, another upload box pops up and so on and so on. And then, i use phpmailer to send the files as email attachments. Look up phpmailer for more details...
The javascript to add more upload fields.. (put in HEAD)
<script type="text/javascript">
function addElement()
{
var ni = document.getElementById('org_div1');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newDiv = document.createElement('div');
var divIdName = num; newDiv.setAttribute('id',divIdName);
newDiv.innerHTML = '<input type="file" class="fileupload" size="80" name="file' + (num) + '" onchange="addElement()"/> <a class="removelink" onclick=\'removeElement(' + divIdName + ')\'>Remove This File</a>';
// add the newly created element and it's content into the DOM
ni.appendChild(newDiv);
}
function removeElement(divNum)
{
var d = document.getElementById('org_div1');
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}
</script>
The HTML..
<div id="org_div1" class="file_wrapper_input">
<input type="hidden" value="1" id="theValue" />
<input type="file" class="fileupload" name="file1" size=
"80" onchange="addElement()" /></div>
The process.php page. NOTE: MUST EDIT!!! Search phpmailer and download their class.phpmailer.css class. Edit the configs in the file. Create and "uploads" directory.
<?php
require("css/class.phpmailer.php");
//Variables Declaration
$name = "Purchase Form";
$email_subject = "New Purchase Ticket";
$body = "geg";
foreach ($_REQUEST as $field_name => $value){
if (!empty($value)) $body .= "$field_name = $value\n\r";
}
$Email_to = "blank#blank.com"; // the one that recieves the email
$email_from = "No reply!";
//
//==== PHP Mailer With Attachment Func ====\\
//
//
//
$mail = new PHPMailer();
$mail->IsQmail();// send via SMTP MUST EDIT!!!!!
$mail->From = $email_from;
$mail->FromName = $name;
$mail->AddAddress($Email_to);
$mail->AddReplyTo($email_from);
foreach($_FILES as $key => $file){
$target_path = "uploads/";
$target_path = $target_path .basename($file['name']);
if(move_uploaded_file($file['tmp_name'], $target_path)) {
echo "the file ".basename($file['name'])." has been uploaded";
}else {
echo "there was an error";
}
$mail->AddAttachment($target_path);
}
$mail->Body = $body;
$mail->IsHTML(false);
$mail->Subject = $email_subject;
if(!$mail->Send())
{ echo "didnt work";
}
else {echo "Message has been sent";}
foreach($_FILES as $key => $file){
$target_path = "uploads/";
$target_path = $target_path .basename($file['name']);
unlink($target_path);}
}
?>
Let me know if you have any questions!!
Check out the jQuery Mulitple File Upload Plugin. The Uploading multiple files page in the PHP documentation will give you an idea what the submitted result looks like and some examples for working with it.

Categories