PHP Mail form not sending emails on Linux server - php

This is my code and my form... it acts like the email was sent, but it never arrives.
I would like to know what could possibly be wrong... Anyone?
The website is hosted on a Linux server, and I don't really know if the server could be blocking the emails because of some kind of incompatibility... I don't really know what it could be.
<?php
if($_POST)
{
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
die();
}
$to_Email = "myemail#gmail.com"; //Replace with recipient email address
$subject = 'Ah!! My email from Somebody out there...'; //Subject line for emails
//check $_POST vars are set, exit if any missing
if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userPhone"]) || !isset($_POST["userMessage"]))
{
die();
}
//Sanitize input data using PHP filter_var().
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Phone = filter_var($_POST["userPhone"], FILTER_SANITIZE_STRING);
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error.
{
header('HTTP/1.1 500 Name is too short or empty!');
exit();
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
header('HTTP/1.1 500 Please enter a valid email!');
exit();
}
if(!is_numeric($user_Phone)) //check entered data is numbers
{
header('HTTP/1.1 500 Only numbers allowed in phone field');
exit();
}
if(strlen($user_Message)<5) //check emtpy message
{
header('HTTP/1.1 500 Too short message! Please enter something.');
exit();
}
//proceed with PHP email.
$headers = 'From: '.$user_Email.'' . "rn" .
'Reply-To: '.$user_Email.'' . "rn" .
'X-Mailer: PHP/' . phpversion();
#$sentMail = mail($to_Email, $subject, $user_Message .' -'.$user_Name, $headers);
if(!$sentMail)
{
header('HTTP/1.1 500 Couldnot send mail! Sorry..');
exit();
}else{
echo 'Hi '.$user_Name .', Thank you for your email! ';
echo 'Your email has already arrived in my Inbox, all I need to do is Check it.';
}
}
?>
Here's my form:
<fieldset id="contact_form">
<legend>My Contact Form</legend>
<div id="result"></div>
<input type="text" name="name" id="inputt" placeholder="Enter Your Name" />
<input type="text" name="email" id="inputt" placeholder="Enter Your Email" />
<input type="text" name="phone" id="inputt" placeholder="Phone Number" />
<textarea name="message" id="message" placeholder="Enter Your Name"></textarea>
<button class="submit_btn" id="submit_btn">Submit</button>
</fieldset>

Your $headers are wrong, you're appending "rn" instead of "\r\n". Try this instead:
$headers = 'From: '.$user_Email. "\r\n" .
'Reply-To: '.$user_Email. "\r\n" .
'X-Mailer: PHP/' . phpversion();

According from your comment out of the maillog you need to adjust your php.ini to include the --r argument to your sendmail_path.
By default it usually is:
sendmail_path = /usr/sbin/sendmail -t -i
Apparently you are using another argument that also requires the --r argument. Appending that to your sendmail_path should get a long way.

Related

display a message after submit and refresh

i'm trying to get a message to appear after my form has been submitted, i can get the form to submit and the page to then refresh but unsure how to add the message after the refresh.
i have no knowledge of PHP so sorry is its and obvious answer
thanks
my html & PHP if needed
<form action="action.php" method="POST" target="my_iframe" onsubmit="setTimeout(function(){window.location.reload();},10);">
<input type="text" id="name" name="name" placeholder="name" required="required">
<input type="email" id="email" name="email" placeholder="email" required="required">
<input type="tel" id="phone" name="phone" placeholder="phone">
<div class="form-row" style="display:none;"><input type="hidden" name="url" placeholder="URL"></div>
<textarea id="message" name="message" placeholder="message" style="height:200px" required="required"></textarea>
<input id="submit" type="submit" value="submit">
</form>
<iframe name="my_iframe" width="1" height="1" style="border:none"></iframe>
<?php
$to = 'zoeharrisondesign#gmail.com';
$subject = 'New Message Recieved!';
$from = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$name = $_POST['name'];
//check honeypot
if( !empty( $honeypot ) ) {
echo 'There was a problem';
}
// 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";
// Create email headers
$headers .= 'From: '.$from."\r\n".
'Reply-To: '.$from."\r\n" .
'X-Mailer: PHP/' . phpversion();
// Compose a simple HTML email message
$message = "$message \r\n |
From $name \r\n |
Tel: $phone";
// Sending email
if(mail($to, $subject, $message, $headers)){
echo 'Your message has been sent successfully.';
} else{
echo 'Unable to send email. Please try again.';
}
?>
Update your php sending email to this
if (mail($myEmail, $subject, $message)){
$success = "Message sent successful";
}else{
$success = "Message Sending Failed.";
}
Then add this php codes in your html codes add this code to display a message. Put it on top of your form html tag.
<?php
if (isset($success)){ echo "<div>" . $success . "</div>";}
?>
You may even add some styling on the message if you prefer.

Getting error when the contact form be submitted

Getting error when the contact form should be submitted.
Undefined index: HTTP_X_REQUESTED_WITH in C:\xampp\htdocs\dishadwellings\dishaparkwest\contact.php on line 7
{"type":"error","text":"Sorry Request must be Ajax POST"}
Here is the HTML FORM code:
<form action="contact.php" method="POST">
<input type="text" name="do-input-name" id="do-input-name" placeholder="Name">
<input type="email" name="do-input-email" id="do-input-email" placeholder="Email">
<input type="text" name="do-input-web" id="do-input-web" placeholder="Web">
<textarea name="do-input-message" id="do-input-message" cols="30" rows="10" class="do-input-message" placeholder="Comment"></textarea>
<button type="submit" id="do-submit-btn" class="do-btn-round-solid">SEND</button>
</form>
Here is the code for the contact form: I could not rectify the error. Kindly do the favour to solve this issue
<?php
if($_POST)
{
$to_email = "abc#gmail.com"; //Recipient email, Replace with own email here
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST["message"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($name)<4){ // If length is less than 4 it will output JSON error.
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ //email validation
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if(strlen($message)<3){ //check emtpy message
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
//email body
$message_body = $message."\r\n\r\n-".$name."\r\nEmail : ".$email;
//proceed with PHP email.
$headers = 'From: '.$name.'' . "\r\n" .
'Reply-To: '.$email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$send_mail = mail($to_email, $subject, $message_body, $headers);
if(!$send_mail)
{
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_name .' Thank you for your email'));
die($output);
}
}
?>
Try your if condition as follow:
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || ( isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')) {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
The next thing is, you are submitting form via normal HTML form and you are trying to check that submit data OR send email only if its ajax submit. which is not truth and so it not works.
To make your code working, either submit your form data via ajax OR remove this if condition shown above.
Your post code
<?php
if($_POST)
{
$to_email = "abc#gmail.com"; //Recipient email, Replace with own email here
//Sanitize input data using PHP filter_var().
$name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST["message"], FILTER_SANITIZE_STRING);
$subject = "Test email";
$user_name = "Sharnya";
//additional php validation
if(strlen($name)<4){ // If length is less than 4 it will output JSON error.
$output = 'Name is too short or empty!';
die($output);
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ //email validation
$output = 'Please enter a valid email!';
die($output);
}
if(strlen($message)<3){ //check emtpy message
$output = 'Too short message! Please enter something.';
die($output);
}
//email body
$message_body = $message."\r\n\r\n-".$name."\r\nEmail : ".$email;
//proceed with PHP email.
$headers = 'From: '.$name.'' . "\r\n" .
'Reply-To: '.$email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$send_mail = mail($to_email, $subject, $message_body, $headers);
if(!$send_mail)
{
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = 'Could not send mail! Please check your PHP mail configuration.';
die($output);
}else{
$output = 'Hi '.$user_name .' Thank you for your email';
die($output);
}
}
?>
HTML form code:
<form action="contact.php" method="POST" enctype="text/plain">
<input type="text" name="name" id="name" placeholder="Name">
<input type="email" name="email" id="email" placeholder="Email">
<input type="text" name="web" id="web" placeholder="Web">
<textarea name="message" id="message" cols="30" rows="10" class="message" placeholder="Comment"></textarea>
<button type="submit" id="submit" class="do-btn-round-solid">SEND</button>
</form>
Happy coding!

I am attempting to create a working PHP contact form

At the bottom of this page under the section 'Quick Message' in the lower right there is a a contact form I'm trying to fix.
http://danielgruttadaro.chapter7ny.com
The form does not allow submissions that do not have all three sections filled out. However, I am receiving the error: 'sorry unexpected error please try again later' when the form is properly filled out. Below is the relevant html and php. Thanks for your help.
<form method="post" action="contact.php" id="contactform">
<div class="form">
<input class="col-md-6" type="text" name="name" placeholder="Name">
<input class="col-md-6" type="text" name="email" placeholder="E-mail">
<textarea class="col-md-12" name="message" rows="4" placeholder="Message"></textarea>
<input type="submit" id="submit" class="btn" value="Send">
</div>
Here is the php:
<?php
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$message = ($_GET['message']) ?$_GET['message'] : $_POST['message'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//Simple server side validation for POST data, of course, you should validate the email
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$email) $errors[count($errors)] = 'Please enter your email.';
if (!$message) $errors[count($errors)] = 'Please enter your message.';
//if the errors array is empty, send the mail
if (!$errors) {
//recipient - replace your email here
$to = 'dan#chapter7ny.com';
//sender - from the form
$from = $name . ' <' . $email . '>';
//subject and the html message
$subject = 'Message from ' . $name;
$message = 'Name: ' . $name . '<br/><br/>
Email: ' . $email . '<br/><br/>
Message: ' . nl2br($message) . '<br/>';
//send the mail
$result = sendmail($to, $subject, $message, $from);
//if POST was used, display the message straight away
if ($_POST) {
if ($result) echo 'Thank you! We have received your message.';
else echo 'Sorry, unexpected error. Please try again later';
//else if GET was used, return the boolean value so that
//ajax script can react accordingly
//1 means success, 0 means failed
} else {
echo $result;
}
//if the errors array has values
} else {
//display the errors message
for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
echo 'Back';
exit;
}
//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
if ($result) return 1;
else return 0;
}
?>
Most likely the machine that is running php doesn't have a mail server set up as well. The mail function requires that. You can use a library like:
https://github.com/PHPMailer/PHPMailer
and use an existing gmail account to send your email:
http://phpmailer.worxware.com/?pg=examplebgmail
which will let you mail yourself whatever they type in. This is what I use in almost all of my projects.
You can also use PEAR:
https://pear.php.net/package/Mail
Which I have also had luck with in the past. Godspeed.

What is wrong with my contact from?

On my website there is a contact form, for some reason after filling out the form, I won't get an email.
Below is the code for the form followed by the code for the sendmail.php code page. *For privacy I removed my email and replaced it with email#domain.com
Anyone know what could be wrong?
Thanks in advance,
Peter
contact.html Page Snip --
<div class="contact-us container">
<div class="row">
<div class="contact-form span7">
<p>Please fill out the form below and we'll get back to you as soon as we can! </p>
<form method="post" action="assets/sendmail.php">
<label for="name" class="nameLabel">Name</label>
<input id="name" type="text" name="name" placeholder="Enter your name...">
<label for="email" class="emailLabel">Email</label>
<input id="email" type="text" name="email" placeholder="Enter your email...">
<label for="subject">Subject</label>
<input id="subject" type="text" name="subject" placeholder="Your subject...">
<label for="message" class="messageLabel">Message</label>
<textarea id="message" name="message" placeholder="Your message..."></textarea>
<button type="submit">Send</button>
</form>
</div>
</div>
</div>
Sendmail.php --
// Email address verification
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|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($_POST) {
// Enter the email where you want to receive the message
$emailTo = 'email#doamin.com';
$clientName = trim($_POST['name']);
$clientEmail = trim($_POST['email']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
$array = array();
$array['nameMessage'] = '';
$array['emailMessage'] = '';
$array['messageMessage'] = '';
if($clientName == '') {
$array['nameMessage'] = 'Please enter your name.';
}
if(!isEmail($clientEmail)) {
$array['emailMessage'] = 'Please insert a valid email address.';
}
if($message == '') {
$array['messageMessage'] = 'Please enter your message.';
}
if($clientName != '' && isEmail($clientEmail) && $message != '') {
// Send email
$headers = "From: " . $clientName . " <" . $clientEmail . ">" . "\r\n" . "Reply-To: " . $clientEmail;
mail($emailTo, $subject, $message, $headers);
}
echo json_encode($array);
}
?>
Try changing if($_POST) to if( ! empty($_POST)). Also try var_dump($_POST); at the top of the page to make sure you're getting the variables through properly.
In my working contact form in php i use following verification:
if(isset($_POST['email']))
{
// your send mail code
}
BTW if you call directly:
mail("youremail#domain" , " your subject" , " mail body" , "From: example#example.com" );
your mail arives in inbox? i ask because you may not have acces to sendmail function from php.
1. Using
Your'e using PHP - Why you dont use functions that provides by PHP?
isEmail is nonsense, use filter_var to validate E-Mails:
if(filter_var($clientEmail, FILTER_VALIDATE_EMAIL)) {
// E-Mail is valid
}
2. POST Requests
To check if the post-request is taken, use isset or empty:
if(isset($_POST)) {
// Send the mail...
}
If you're using more than one form with an POST-Request on your side, be sure that you only handle the correct form. To prevent the problem, add an name attribute on your submit-button and check it:
if(isset($_POST['yourFirstButton'])) {
// Handle the first form
}
And
<input type="submit" name="yourFirstButton" value="Send" />
3. Use correct mail headers
Mail-Headers must be valid. A Propertie is Name: Value\r\n and NOT Name: Value.
You must add an \r\n at your last entry:
$headers = "From: " . $clientName . " <" . $clientEmail . ">" . "\r\n" . "Reply-To: " . $clientEmail . "\r\n";
4. Can your server send mails?
If you dont receive mails, check your server configuration or ask your server administrator. PHP must be configured to sending mails. Install sendmail for example. Otherwise fill out the SMPT settings in your PHP-Configuration (php.ini) to send a mail over an mailserver.
5. Using mail
Why you use the mail function? Mostly you (the programmer) must deal with headers and other to send a valid mail - Otherwise, the mailserver decline/bounce the mail or the mail goes to your spam folder.
If you're using mail, check the output:
$test = mail(/* Your parameters */);
var_dump($test);
If it's returned 1 or true, PHP says that the mail was probably sent.
Use an PHP Mailer class like PHPMailer (https://github.com/PHPMailer/PHPMailer)

HTML form working but need a php validation

i need a help with this. What i need to do to validate the email in this form? This is a landing page, I want to get the email of a visitor before he/she can visit my content here is this demo.
Can I get some tips or the right code to use for this page?
<form id="contact-form" action="send.php">
<input type="text" name="email" placeholder="you#yourmail.com" class="cform-text" size="40" title="your email" required>
<input type="submit" value="Enter Now" class="cform-submit">
</form>
send.php file:
$visitorEmail = $_GET['email'];
$email_from = "doctordongok#gmail.com";
$email_subject = "New Form Submission! - From: " + $visitorEmail;
// edit here
$email_body = "New visitor - $visitorEmail";
$to = "doctordongok#gmail.com";
$headers = "From: $email_from \r \n";
$headers .= "Reply-To: $visitorEmail \r \n";
mail($to, $email_subject, $email_body, $headers);
header("Location: http://www.de-signs.com.au");
Thank you!
Use the filter_var() function of PHP:
if(filter_var($visitorEmail, FILTER_VALIDATE_EMAIL) === false) {
// Invalid E-Mail address
} else {
// OK
}
So to mockup your new script. It will look something like this
$visitorEmail = $_GET['email'];
if(filter_var($visitorEmail, FILTER_VALIDATE_EMAIL) === false) {
die('Sorry that\'s no valid e-mail address');
} else {
$email_from = 'doctordongok#gmail.com';
$email_subject = 'New Form Submission! - From: ' . $visitorEmail;
// edit here
$email_body = 'New visitor - ' . $visitorEmail;
$to = 'doctordongok#gmail.com';
$headers = 'From: $email_from' . PHP_EOL;
$headers .= 'Reply-To: $visitorEmail' . PHP_EOL;
mail($to, $email_subject, $email_body, $headers);
header('Location: http://www.de-signs.com.au');
exit;
}
Your best bet is probably to validate on the client side using a Javascript and on the server side as well using a regular expression on both ends.
Validating an email with Javascript
HTML5's new email type for input is here to help you.
<input type="email" name="email" placeholder="you#yourmail.com" class="cform-text" size="40" title="your email" required />

Categories