The PHP script is not sending emails to my account - php

Can anyone please help me with this php code. I am using a php code in my contact us page to send an email to my account. Somehow the code is not working. The basic function of this code is to capture the details inputted by an user and send the details to my email account. But somehow the PHP code is executing and not showing any error but is not sending email to my account. So, anyone please suggest me where i am going wrong... Thanks all...
Here is the PHP code which i am using:
<?php
error_reporting(0);
error_reporting (E_NONE);
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$mob_no = $_POST['mob_no'];
$email = $_POST['email'];
$course = $_POST['course'];
$location = $_POST['location'];
$city = $_POST['city'];
$to = "example#mywebsite.com";
$subject = 'Request Assistance';
$headers = array();
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset = iso-8859-1';
$headers[] = 'Content-Transfer-Encoding: 7bit';
$headers[] = 'From: ' . $first_name . " " . $last_name;
$message .= "First Name: " . $first_name . "\n";
$message .= "Last Name: " . $last_name . "\n";
$message .= "Mobile No: " . $mob_no . "\n";
$message .= "E-Mail: " . $email . "\n";
$message .= "Course: " . $course . "\n";
$message .= "Location: " . $location . "\n";
$message .= "City: " . $city . "\n";
?>
<?php
$success = mail($to, $subject, $message, $headers);
if (($_POST['first_name'] == "") || ($_POST['last_name'] == "") || ($_POST['mob_no'] == "") || ($_POST['email'] == "") || ($_POST['course'] == "") || ($_POST['location'] == "") ||($_POST['city'] == "")) {
echo '<h1>Sorry for the inconvenience!</h1>';
echo '<p>We have encountered a problem, Please Note:<br />';
echo 'Make sure you fill in all the details<br />';
echo 'Do not use spaces or special characters, except in E-Mail.<br />';
echo 'Inconvenience is deeply regretted!!!</p>';
}
if ((!ctype_alpha($first_name)) || (!ctype_alpha($last_name)) || (!ctype_digit($mob_no)) || (!ctype_alpha($course)) || (!ctype_alpha($location)) || (!ctype_alpha($city))) {
echo '<h1>Sorry for the inconvenience!</h1>';
echo '<p>We have encountered a problem, Please Note:<br />';
echo 'Make sure you fill in all the details<br />';
echo 'Do not use spaces or special characters, except in E-Mail.<br />';
echo 'Inconvenience is deeply regretted!!!</p>';
}
if ($success) {
echo '<h1>Congratulations!</h1>';
echo '<p>The following message has been sent:<br /><br />';
echo '<b>To:</b> ' . $to . '<br />';
echo '<b>From:</b> ' . $email . '<br />';
echo $message;
}
?>

Your code itself doesn't look wrong to me, see following:
1. Make sure your host enables mail function
2. Using mail may result in the junk folder sometimes as many spam uses this
3. Try using phpmailer, similar to mail but more configurable

Related

How to implement reCAPTCHA in a current PHP email form

I am new to PHP, but know my way around HTML. I have been asked to implement a reCaptcha form into our site's PHP contact email form. I'm coming up empty. I have signed up and have my site key and secret key, just no idea how to integrate it into our form.
Here is our sites PHP form:
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
if(trim($name) == '') {
echo '<div class="error_message">Please enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Please enter a valid email address.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">You have entered an invalid e-mail address, try again.</div>';
exit();
}
if(trim($comments) == '') {
echo '<div class="error_message">Please enter your message.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "yourname#yourdomain.com";
$address = "contact#########.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name from your website, their message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name by email, $email or by phone $phone";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h2>Email Sent Successfully.</h2>";
echo "<p>Thank you <strong>$name</strong>, your message has been sent to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
Any help is appreciated. Thanks!
First, as a part of your form elements, include reCaptcha:
<?php
require_once("location/of/recaptchalib.php");
$publickey = "yourPublicKeyGoesHere";
echo recaptcha_get_html($publickey);
?>
in your send_email.php file you can do this:
<?php
session_start();
require_once("location/of/recaptchalib.php");
$timezone = "Asia/Kuwait";
if(function_exists('date_default_timezone_set')) date_default_timezone_set($timezone);
$privatekey = "YourPrivateKey";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]
);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
}
else {
$sender_name = $_POST['sender_name'];
$sender_email = $_POST['sender_email'];
$query_type = $_POST['query_type'];
$ip = $_SERVER["REMOTE_ADDR"];
$date = date("d M Y H:i:s");
$sender_message = "Thank You for your message, ".$sender_name."\r\n"."Message was sent from ".$ip."on ".$date."\r\n".$_POST['sender_message'];
$headers = "From: Your Website" . "\r\n" .
"BCC: you#yourwebsite.com";
mail($sender_email,'Email from yourwebsite guest',$sender_message,$headers);
echo "Message Sent!";
}
?>
This worked for me, and the form looks like this:
I hope this helps.

PHP form data not submitting with recaptcha

I'm having some trouble setting up the recaptha with my limited PHP knowledge. I have managed to get it working in essence, but am finding that know my form data is not submitting.
Here is the PHP as it stands:
<?php
$sendToEmail="my#emailaddress.co.uk";
$yourname = $_POST["yourname"];
$timecall = $_POST["timecall"];
$email=$_POST["email"];
$phone=$_POST["phone"];
$message=$_POST["message"];
$content = "Time to Call : " . $timecall . "<br>";
$content .= "Name : " . $yourname . "<br>";
$content .= "Email : " . $email . "<br>";
$content .= "Phone : " . $phone . "<br>";
$content .= "Message : ". $message ."<br>";
$senderEmailId = "Reply-To: $email";
$senderEmailId = "From: $email\r\n";
$senderEmailId .= "Content-type: text/html\r\n";
$subject ="New Enquiry from the website";
if(isset($_POST['ContactButton'])) {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "--private-key--";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST[g-recaptcha-response]."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if (isset($data->success) AND $data->success==true) {
//// True- what happens when user is verified
header("Location:thankyou.php?CaptchaPass=True");
}else{
header("Location:thankyou.php?CaptchaFail=True");
}
}
?>
Thank you in advance!
PHP 101: array key strings which aren't quoted are treated as undefined constants. You have:
$_POST[g-recaptcha-response]
which is parsed/executed as
$_POST[g minus recaptcha minus response]
$_POST[0 minus 0 minus 0]
$_POST[0]
If you had PHP's debug options enabled (error_reporting, display_errors), you'd have been given warnings about this. These settings should NEVER be off on a debug/devel server in the first place.
Try
$_POST['g-recaptcha-response']
^--------------------^
instead. Note the quotes.

sendmail.php does not work on mobile

Strange issue - my sendmail.php is working perfectly on desktop and on mobile devices only when requesting desktop websites (in Chrome app), but when using mobile site he does not work at all.
Can someone help me figure this out?
here is the code:
<?php
if(isset($_POST['email'])) {
if (!check_email($_POST['email']))
{
echo 'Please enter a valid email address<br />';
}
else send_email();
}
exit;
function check_email($emailAddress) {
if (filter_var($emailAddress, FILTER_VALIDATE_EMAIL)) {
return TRUE;
} else {
return FALSE;
}
}
function send_email() {
$message = "\nName: " . $_POST['name'] .
"\nEmail: " . $_POST['email'] ;
$message .= "\nMessage: " . $_POST['comment'] .
"\n\nBrowser Info: " . $_SERVER["HTTP_USER_AGENT"] .
"\nIP: " . $_SERVER["REMOTE_ADDR"] .
"\n\nDate: " . date("Y-m-d h:i:s");
$siteEmail = $_POST['receiver'];
$emailTitle = $_POST['subject'];
$thankYouMessage = "Thank you for contacting us, we'll get back to you shortly.";
if(!mail($siteEmail, $emailTitle, $message, 'From: ' . $_POST['name'] . ' <' . $_POST['email'] . '>'))
{
echo 'error';
}
else
{
echo 'success';
}
}
?>
You must make sure the mobile form has these two elements:
It is being submitted using method="POST".
Your email input has the attribute and value name="email".
I demonstrate where these things are set in the following code. This is incomplete, of course, it's just designed to show you where the two required parts must be.
<form ... method="POST">
...
<input type="text" name="email" ... >
...
</form>
I need to mention one more thing ...
That being said, what you're doing here is EXTREMELY INSECURE. You are allowing someone to set an email's from and two address on a web form. A (not so) clever hacker can easily write a script to turn your server into an open relay for spam or other evil activities. At minimum, you should remove $_POST['receiver'] and replace with with a hard-coded email address or at least not something that can be altered by an end-user when they POST to your form.
So I drilled down and found that the mobile form is directing submissions through this PHP file which was 404.
The issue now is, even when this file is avaiable, emails are not sent...
' . "\r\n"; $headers .=
'From: ' . "\r\n"; $headers = 'MIME-Version: 1.0' .
"\r\n"; $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$message .= "Name: " . $name . ""; $message .= "Subject: "
. $subject . ""; $message .= "Email: " . $email . ""; $message .= "Message: " . $message_text . "";
mail($to, $subject, $message, $headers, "-f noreplay#info.com");
echo 1; }
if(isset($_POST['sendmail']) && $_POST['sendmail'] == 1){
send_mail(); } ?>

Multiple field PHP form submission

The problem I'm having is that I want to pass through data from a number of fields in a form into one email send via PHP, the concerned code is as follows:
$mailcheck = spamcheck($_POST['inputemail']);
if ($mailcheck==FALSE)
{
echo "Invalid input";
}
else
{
// This still needs to be debugged online as soon as possible
$from = $_POST['inputemail'];
$name = $_POST['inputname'];
$phone = $_POST['inputphone'];
$date = $_POST['inputdate'];
$time = $_POST['inputtime'];
$data = $_POST['inputprotection'];
$subject = $_POST['inputdropdown'];
$message = $_POST['inputmessage'];
$message = wordwrap($message, 70);
mail("UP498701#myport.ac.uk",$subject,$message,"From: $from\n" . "Name: $name\n" . "Phone: $phone\n" . "Date: $date\n" . "Time: $time\n" . "Keep Data? $data\n");
echo "Thank you for sending us feedback, you'll be redirected in 5 seconds";
}
}
This is where I'm declaring all the information to be passed as a header for the email. The current PHP passes syntax check as works to the extent that an email is sent containing the $to, $subject, $message all fine, but the $header only passes through the final part (Keep Data? $data\n). When I remove all the other fields and simply keep the $data part, the email stops sending any $header. I also have an issue with the redirect, which has been removed from the below code and will be inserted as soon the current issue is resolved. The current full PHP is:
<html>
<body>
<?php
function spamcheck($field)
{
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
?>
<?php
if (isset($_POST['inputemail']))
{
$mailcheck = spamcheck($_POST['inputemail']);
if ($mailcheck==FALSE)
{
echo "Invalid input";
}
else
{
// This still needs to be debugged online as soon as possible
$from = $_POST['inputemail'];
$name = $_POST['inputname'];
$phone = $_POST['inputphone'];
$date = $_POST['inputdate'];
$time = $_POST['inputtime'];
$data = $_POST['inputprotection'];
$subject = $_POST['inputdropdown'];
$message = $_POST['inputmessage'];
$message = wordwrap($message, 70);
mail("UP498701#myport.ac.uk",$subject,$message,"From: $from\n" . "Name: $name\n" . "Phone: $phone\n" . "Date: $date\n" . "Time: $time\n" . "Keep Data? $data\n");
echo "Thank you for sending us feedback, you'll be redirected in 5 seconds";
}
}
?>
</body>
and is temporarily hosted at http://luke-hale.com/temp/contact.html. I'm sure this is just a case of being misinformed on my part, but any help would be great, cheers!
EDIT:
okay so that issue is sorted with:
$subject = $_POST['inputdropdown'];
$message = $_POST['inputmessage'] . "\r\n\r\n" . $_POST['inputname'];
$message = wordwrap($message, 70);
$headers = "From: " . $_POST['inputemail'];
mail("UP498701#myport.ac.uk",$subject,$message,$headers);
echo "Thank you for sending us feedback, you'll be redirected in 5 seconds";
Which works though doesn't display the $headers anywhere, but I'm not too fussed about this, the next thing is the redirect, which I would usually run through via:
header("refresh:5;url=http://www.domain.com")
Though this was not working correctly earlier, I will apply an edit when tested for anyones future reference.
EDIT
So the form works but the re-direct does not. The site is still hosted on the same domain, but now the full PHP looks like this:
<html>
<body>
<?php
function spamcheck($field)
{
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
?>
<?php
if (isset($_POST['inputemail']))
{
$mailcheck = spamcheck($_POST['inputemail']);
if ($mailcheck==FALSE)
{
echo "Invalid input";
}
else
{
$subject = $_POST['inputdropdown'];
$message = "Name: " . $_POST['inputname'] . "\r\n\r\n" . "Email: " . $_POST['inputemail'] . "\r\n\r\n" . "Phone: " . $_POST['inputphone'] . "\r\n\r\n" . "Date: " . $_POST['inputdate'] . "\r\n\r\n" . "Time: " . $_POST['inputtime'] . "\r\n\r\n" . "Retain Data? " . $_POST['inputprotection'] . "\r\n\r\n" . "Message: " . $_POST['inputmessage'];
$message = wordwrap($message, 70);
$headers = "From: " . $_POST['inputemail'];
mail("UP498701#myport.ac.uk",$subject,$message,$headers);
echo "Thank you for sending us feedback, you'll be redirected in 5 seconds";
}
}
header("refresh:5;url=http://www.domain.com")
?>
</body>
The form still sends fine but the return states that the line beginning "header" cannot be passed because the browser data has already been modified. I'm not sure sure what I've done or where so if anyone could lend a hand, that'd be great!
FINAL EDIT
My final, fully working, code:
<?php
function spamcheck($field)
{
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
?>
<?php
ob_start();
if (isset($_REQUEST['inputemail'])&&($_REQUEST['inputname'])&&($_REQUEST['inputmessage']))
{
$mailcheck = spamcheck($_POST['inputemail']);
if ($mailcheck==FALSE)
{
echo "Invalid email, you'll be redirected ";
header("refresh:5;url=http://www.luke-hale.com/");
}
else
{
$subject = $_POST['inputdropdown'];
$message = "Name: " . $_POST['inputname'] . "\r\n\r\n" . "Email: " . $_POST['inputemail'] . "\r\n\r\n" . "Phone: " . $_POST['inputphone'] . "\r\n\r\n" . "Date: " . $_POST['inputdate'] . "\r\n\r\n" . "Time: " . $_POST['inputtime'] . "\r\n\r\n" . "Retain Data? " . $_POST['inputprotection'] . "\r\n\r\n" . "Message: " . $_POST['inputmessage'];
$message = wordwrap($message, 70);
$headers = "From: " . $_POST['inputemail'];
mail("UP498701#myport.ac.uk",$subject,$message,$headers);
echo "Thank you for your messgae, I'll get back to you as soon as possible! You'll be redirected in 5 seconds.";
}
header("refresh:5;url=http://www.luke-hale.com/");
}
else
{
echo "You did not fill all the required fields, please try again.";
header("refresh:5;url=http://www.luke-hale.com/");
}
?>
Try putting your form data into the $message variable, insert \n after each attribute to give a new line. Do not use the header.
Location and Refresh both require an absolute URI
header('Location: http://www.domain.com');
Examples for mail:
https://stackoverflow.com/a/22833890/3489793
https://stackoverflow.com/a/22831825/3489793
mail("Your Email Address Here",$subject,$therest,"subject: $subject\n");
U said this:
"The mail function is also not the issue, and correct syntax is" mail($to,$subject,$message,$headers,$parameters)
Explanation:
your email adress = $to
$subject = $subject
$therest = $message (rename it if you want)
"subject: $subject\n" = the header (change it to $headers if you want that)
Header example (as in the documentation)
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
You could echo a Javascript at the bottom of your PHP script which redirects instead, like this:
$url = "url";
$time = 5000 // time in milliseconds
print "<script>window.setTimeout(function(){window.location='".$url."'},".$time.") </script>"

how do i send a form with php and once the contact info is sent it goes to another url?

what i want to do is when i click on submit it goes to the index page and dont stay on the php page
this is my code
$name = $_POST[\'name\'];
$email = $_POST[\'email\'];
$phone = $_POST[\'phone\'];
$reason = $_POST[\'reason\'];
$header = \'From: \' . $email . \" \\r\\n\";
$msg = \"Sent from: \" . $name . \"\\r\\n\";
$msg .= \"Email: \" . $email . \" \\r\\n\";
$msg .= \"Phone: \" . $phone . \" \\r\\n\";
$msg .= \"Contact reason:\" . $reason . \" \\r\\n\";
$msg .= \"Message: \" . $_POST[\'message\'] . \" \\r\\n\";
$msg .= \"Date and time \" . date(\'d/m/Y\', time());
$to = \'emailhere#something.com\';
$subject = \'contact page\';
mail($to, $subject, utf8_decode($msg), $header);
echo \'The Message is sent\';
i wonder if somebody can help me? i think isnt too hard right?
header("Location: http://www.example.com/");
see http://php.net/manual/de/function.header.php for more info
You can use header("Location: http://www.yoursite.com/index.php") to redirect to
the index.php of your website.
The header() method must be called before any issue like the echo \'The Message is sent\';
Why do you escape all those quotes?
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$reason = $_POST['reason'];
$header = 'From: ' . $email . "\r\n";
$msg = "Sent from: " . $name . "\r\n";
$msg .= "Email: " . $email . "\r\n";
$msg .= "Phone: " . $phone . "\r\n";
$msg .= "Contact reason:" . $reason . "\r\n";
$msg .= "Message: " . $_POST['message'] . "\r\n";
$msg .= "Date and time " . date(\'d/m/Y\', time());
$to = 'emailhere#something.com';
$subject = 'contact page';
mail($to, $subject, utf8_decode($msg), $header);
// redirect to page
$url = 'http://example.com';
header('Location: '.$url); // must be used before any output to the browser
die; // prevent execution of other code
You only need to escape quotes you want to display in string.
e.g.:
$test = "This is a \"test\".";
Will display:
This is a "test"
Or you can do:
$test = 'This is a "test"';

Categories