php is sending invalid email address - php

Hello after 3 days of trying to put my form together, I have come across a problem...
Using the form, It can validate when i press submit. which is good, but once i press send, the invalid data still gets sent to my inbox.. so I will end up with two emails.. one with invalid data and then one with the valid data which is typed in after the error messages have been displayed and re-sent. If anyone can look at my code and see what I am missing, or have done wrong i will appreciate it soo much
<?php
if (isset($_POST['submit'])) {
//check email
if(empty($_POST['email_addr']))
$msg_email = "*";
$email_subject = $_POST['email_addr'];
$email_pattern = '/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/';
preg_match($email_pattern, $email_subject, $email_matches);
if(!$email_matches[0])
$msg2_email = "Please enter a valid email address";
}
// validation complete
if(isset($_POST['submit'])){
if($msg_name=="" && $msg2_name=="" && $msg_email=="" && $msg2_email=="")
$msg_success = "Thankyou for your enquiry";
//send mail
$EmailFrom = "someone#somewhere.com";
$EmailTo = "someone#somewhere.com";
$Subject = "Online contact form";
$email_addr = Trim(stripslashes($_POST['email_addr']));
}
// prepare email body text
$Body = "";
$Body .= "email_addr: ";
$Body .= $email_addr;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: $EmailFrom");
?>

I would not use your regular expression to validate email addresses. I'd use filter_var instead.
if( !filter_var($_POST['email_addr'], FILTER_VALIDATE_EMAIL) ) {
$msg2_email = "Please enter a valid email address";
}
filter_var returns false if the filter fails, otherwise it returns the filtered email address.
On top of that, you can set a default value if your filter fails. For example, suppose that the email address field is not necessary, so instead writing yet another line of code to check for null-ness in your variables like:
$isEmailNull = ( $_POST['email_addr'] === NULL) ? NULL : $_POST['email_addr'];
with filter_var you can write it like:
$emailAddress = filter_var( $_POST['email_addr'], FILTER_VALIDATE_EMAIL,
array('options' => array(
'default' => null
)
));
If your filter fails, then $emailAddress is not false, but null. Which makes more sense for non-boolean variables.
You can read more about filter_var here
you can validate/sanitize IP addresses, URLs, Email addresses, ASCII characters, numbers, etc... without using regular expressions that may or may not work.

Related

Contact form in php doesnt receive mail for hotmail

I m trying contact form in php.I receive the mails in gmail,yahoo etc but doesnt recieve any mails in hotmail.I tried a lot but doesnt know whats the problem.Why i cant recieve mail in hotmail? Here is the code.
if (empty($error)) {
$to = 'abc#gmail.com, ' . $email;
$subject = " contact form message";
$repEmail = 'abc#gmail.com';
$headers = 'From: Contact Detail <'.$repEmail.'>'.$eol;
$content = "Contact Details: \n
Name:$name \n
Batch: $batch \n
Email: $email \n
mobile: $mobile " ;
$success = "<b>Thank you! Your message has been sent!</b>";
mail($to,$subject,$content,$headers);
}
}
?>
Check the server admin's email for bounce messages. I would guess it has to do with hotmail rejecting it either because it doesn't like your host or because you don't have SPF or DKIM signing set up. Either way, the blame is probably on your server email administrator more than on your code. Email is actually kinda complex to set up nowadays given all the anti-spam stuff you have to do.
You might want to consider using a third party email service. SMTP through a gmail account or Amazon SES so they'll take care of more of these details. This can be set up by the server admin too, or done in PHP with libraries. Is there a SMTP mail transfer library in PHP
this is more likely
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
{
//send email
$email = $_REQUEST['email'] ;
$subject = 'Order' ;
$message =
'Product Name :'. $_REQUEST['proname']."\n". //these all are example details
'Name :'.$_REQUEST['name']."\n".
'Phone :'. $_REQUEST['phone']."\n".
'City :'.$_REQUEST['city']."\n".
'Address :'.$_REQUEST['address']."\n".
'Quantity :'. $_REQUEST['select'];
if ($email == "" || $subject == "" || $message == "" )
{
echo 'Please fill the empty fields';
}
else{
mail("anything#something.com", $subject,
$message, "From:" . $email);
echo 'Thank you ! we will contact you soon';
}
}

jquery Contact Form and getting an email with message-text

I made a contact form based on this tutorial but I can't get this one to work.
When I hit the submit button, nothing happens (it seems like the page is being refreshed or on my live website it returns to the index.html) and I don't get an email and no response.
I want to get an email containing the content of the form that the user filled out.
This is the ajaxSubmit.php:
<?php
$name = $_POST['name']; // contain name of person
$email = $_POST['email']; // Email address of sender
$web = $_POST['web']; // Your website URL
$body = $_POST['text']; // Your message
$receiver = "xxx#gmail.com" ; // hardcorde your email address here - This is the email address that all your feedbacks will be sent to
if (!empty($name) & !empty($email) && !empty($body)) {
$body = "Name:{$name}\n\nWebsite :{$web}\n\nComments:{$body}";
$send = mail($receiver, 'Contact Form Submission', $body, "From: {$email}");
if ($send) {
echo 'true'; //if everything is ok,always return true , else ajax submission won't work
}
}
?>
xxx#gmail.com is just a placeholder here for my regular email adress, of course.
FIDDLE with html, js and css.
What am I doing wrong?
I reccomend using isset, to check whether the posted variables actually exists, furthermore: I recommend using the ternary operator to check if they are actually set:
$name = isset($_POST['name']) ? $_POST['name'] : false;
$email = isset($_POST['email']) ? $_POST['email'] : false;
$web = isset($_POST['web']) ? $_POST['web'] : false;
$text = isset($_POST['text']) ? $_POST['text'] : false;
$receiver = "xxx#gmail.com"; // You forgot to close a whitespace here.
if(($name && $email && $web && $text) != false)
{
// It's okay to send email now.
// Checkpoint.
}
I recommend using this spam check filtering function:
function spamcheck($field)
{
//address using FILTER_SANITIZE_EMAIL
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
//address using FILTER_VALIDATE_EMAIL
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return true;
}
else
{
return false;
}
}
And I like to use this modified mail function:
// Usage: sendMail($toEmail, $fromEmail, $subject, $message);
// Pre: $toEmail is of type string and is a valid email address,
// indicating the receiver.
// $fromEmail is of type string and is a valid email address,
// indicating the sender.
// $subject is of type string, indicating the email subject.
// $message is of type string, indicating the message to be send
// via the email, from $fromEmail's address to $toEmail's address.
// Post: An email containing $message and the subject $subject from
// $fromEmail's address to $toEmail's address if $fromEmail
// does not indicate a spam email.
function sendMail($toEmail, $fromEmail, $subject, $message)
{
$validFromEmail = spamcheck($fromEmail);
if($validFromEmail)
{
mail($toEmail, $subject, $message, "From: $fromEmail");
}
}
So you can continue from where we loft off. To begin with: You don't really need the curly braces. Also.. you're overwriting the $body variable, it would make more sense to keep the variables seperated. I also recommend storing the subject in a variable.
$subject = 'Contact Form Submission'; // Place where we left of at Checkpoint.
$message = "Name: $name\n\nWebsite :$web\n\nComments:$body"; // Place where we left of at Checkpoint.
sendMail($email, $receiver, $subject, $message); // Place where we left of at Checkpoint.
You also have to make sure that you have access to a SMTP (Simple Mail Transport Protocol), so it might not be enough for you to be working localhost if you don't have a SMTP server to use. IF you have one, and It's not working, then you might have to config the php ini settings:
ini_set('SMTP' , 'smtp.yourwebsite.com');
ini_set('smtp_port' , '25');
ini_set('username' , 'example#example.com');
ini_set('password' , 'pass');
ini_set('sendmail_from' , 'example#example.com');
Note: It would be smart to actually make the modified mail function RETURN the mail function, so that you can check whether it was successful or not.

Need a PHP email send script for HTML an form

I have a single page portfolio website that I'm building and I have a contact form that I need to process using php send script. I'm a novice when it comes to PHP so I'm having trouble getting this to work. I've done some searching but I can't find what I'm looking for.
Here's what I have done, I copied this from a PHP contact page that I had built but the PHP and form are on the same page and I need an external send.php to process my form.
<?php
$error = ''; // error message
$name = ''; // sender's name
$email = ''; // sender's email address
$company = ''; // company name
$subject = ''; // subject
$comment = ''; // the message itself
if(isset($_POST['send']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$company = $_POST['company'];
$subject = $_POST['subject'];
$comment = $_POST['comment'];
if($error == '')
{
if(get_magic_quotes_gpc())
{
$message = stripslashes($message);
}
// the email will be sent here
// make sure to change this to be your e-mail
$to = "example#email.com";
// the email subject
// '[Contact Form] :' will appear automatically in the subject.
// You can change it as you want
$subject = '[Contact Form] : ' . $subject;
// the mail message ( add any additional information if you want )
$msg = "From : $name \r\ne-Mail : $email \r\nCompany : $company \r\nSubject : $subject \r\n\n" . "Message : \r\n$message";
mail($to, $subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n");
}
}
if(!isset($_POST['send']) || $error != '')
{
header("location: http://www.#.com/#contact");
}
?>
So for my form I want to have:
<form method="post" action="send.php" class="form">
I plan on using HTML5 and jQuery to validate the form, so I really only need the script to capture the info and send the email to a single address. After it sends I want the script to redirect back to the Contact page.
Edit:
I found a solution after spending a while on google.
http://www.website.com/#contact");
?>
For one thing, you haven't initialized the value for $message
$message = stripslashes($message);
You probably meant to use $comment instead of $message
Not sure what problem you're facing. Simply copy the PHP you have into a file called send.php and my first glance says it'll work if you change $message back to $comment and add error checking. If you still have issues, post back with more details.

php email - how to avoid mail ending up in spam box

I have a contact form on my website, which actually works :D
The problem is, that the email ends up in the spam folder. I have tried to do stuff with the header section, but nothing seems to work.
Can anyone help me with this?
thanks
<?php
ini_set("display_errors", "0");
$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS );
$name = $post_data["name"];
$email = $post_data["email"];
$phone = $post_data["phone"];
$website = $post_data["website"];
$message = $post_data["message"];
# select data that needs validation
$validate = array(
'required' => array($name,$email,$message),
'validEmail' => array($email),
'validNumber' => array($phone),
'validAlpha' => array($name)
);
$formcontent = "Name: $name \nE-Mail: $email \nPhone: $phone \nWebsite: $website \nMessage: $message \n";
$formcontent = wordwrap($formcontent, 70, "\n", true);
$recipient = "thomas.teilmann#gmail.com";
$subject = "Contact Messenbrink.eu";
/*$mailheader = "From: $email \r\n";**/
$mailheader .= "Reply-To: $name <$email>\r\n";
$mailheader .= "Return-Path: $name <$email>\r\n";
$mailheader .= "Content-Type: text/plain\r\n";
$mailheader .= "Organization: Sender Organization\r\n";
$mailheader .= "MIME-Version: 1.0\r\n";
$mailheader .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$mailheader .= "X-Priority: 3\r\n";
$mailheader .= "X-Mailer: PHP". phpversion() ."\r\n";
$mailheader .= "From: $name <$email>\r\n";
function sendMail() {
global $formcontent, $recipient, $subject, $mailheader;
mail($recipient, $subject, $formcontent, $mailheader);
}
# error messages
$errorsMsgs = array(
'required' => 'Please fill out all required fields.',
'validEmail' => 'is an invalid email address.',
'validNumber' => 'is an invalid number.',
'validAlpha' => 'contains invalid characters. This field only accepts letters and spaces.'
);
$errorMarkup = "<h1>We found a few errors :-(</h1><h2>Please fix these errors and try again</h2><ol>";
$errorMarkupEnd = "</ol>";
$successMarkup = "<h1>Success!</h1><h2>Your form was sent successfully.</h2>";
$backMarkup = "Back to form";
# begin state
$valid = true;
# loop through fields of error types
foreach ($validate as $type => $fields) {
# loop through values of fields to be tested
foreach ($fields as $value) {
# throw error if value is required and not entered
if ($type === 'required' && strlen($value) === 0) {
$errorMarkup .= "<li>$errorsMsgs[$type]</li>";
$valid = false;
break;
}
else if (
$type === 'validEmail' && !filter_var($value, FILTER_VALIDATE_EMAIL) ||
$type === 'validNumber' && !preg_match('/^[0-9 ]+$/', $value) ||
$type === 'validAlpha' && !preg_match('/^[a-zA-Z ]+$/', $value)
) {
if (strlen($value) === 0) {break;} # skip check if value is not entered
$errorMarkup .= "<li>\"$value\" $errorsMsgs[$type]</li>";
$valid = false;
continue;
}
}
}
if ($valid) {
sendMail();
$body = $successMarkup . $backMarkup;
$title = "Form sent";
} else {
$body = $errorMarkup . $errorMarkupEnd . $backMarkup;
$title = "Form errors";
}
# write html ouput
echo "<!DOCTYPE html><head><title>$title</title><style type=\"text/css\">body{margin:100px;font:16px/1.5 sans-serif;color:#111}h1{font-size:32px;margin:0;font-weight:bold}h2{font-size:18px;margin:0 0 20px 0}ol,li{list-style-position:inside;padding-left:0;margin-left:0}</style></head><body>$body</body></html>";
?>
It has nothing to do with the PHP code but make sure that the email are being sent from a domain that is hosted on the server. That means it would be a bad idea to use your gmail address for sending though PHP. Every email that leaves the server needs to be signed and needs to have SPF records
This is usually because in the DNS a correct SPF record has not been setup. This can be easily done depending on the software you use. If you use cPanel then this is pretty much a two step process.
Some links:
http://www.emailquestions.com/help-desk/2418-why-do-my-own-emails-go-into-spam.html
http://www.google.co.uk/search?sourceid=chrome&ie=UTF-8&q=spf+records
http://www.techtalkpoint.com/articles/setting-up-spf-records-in-cpanel-whm-and-namecheap/
Ensure the message source is valid. Other than that, there isn't a lot you can do in PHP. The rest is down to your message contents, your mail server and the recipient server's spam filter.
Try to ensure that the data in your headers matches what would normally appear in a normal message. For instance, it is best that your From and Return-Path domain name match the server you are sending from.
I notice you just use \n as a line delimiter in the body. It should be \r\n irrespective of the OS you are using.
Ideally, study RFC 2822. If you don't have time to do that, at the very least, compare your headers with other emails that you believe to be valid. Where possible, match the order of headers, including placing the same number of blank lines in the appropriate places.
Spam isn't filtered by some setting, it's filtered by your word choice and how the message looks and also how well known the sender email address is. If you want to avoid the spam list, you have to word it in a way that does not sound spammy.
My one suggestion would be to have the email's From address be the email address of the actual mail account you're using to send these rather than the customer's email account. Your email provider may think they're spoofing if the email comes from their email address but not from a server on that domain.
You could instea put the customer's email address in the body of the email so you know who it's from.
It's probably the smtp being used that is not valid.
If the contact form is just used to send emails to one mailfolder, I would just set up a rule there to not mark it as spam. Either that or actually validate your smtp.
I was having a similar problem with Gmail, I just selected the email and set to "Not Spam" now all emails sent by my server, when someone uses the contact form on my site end up on Inbox folder. Hope this helps.

Why does this validation error occur before data is submitted in PHP form?

I'm using a PHP form to forward data to an email address. Everything seems to work fine except the the error message ["You have not entered an email"] appears when the page is loaded, before any input from the user is entered, rather than through validation when submitted.
The form is here http://www.soulwatt.com/contact.php
Note: I found this PHP code online after doing a search on how to forward data to email, so it is not mine. Please excuse the lack of proper code formatting.
<?php
$to = $_REQUEST['sendto'] ;
$from = $_REQUEST['Email'] ;
$name = $_REQUEST['Name'] ;
$headers = "From: $from";
$subject = "soulwatt.com Contact Data!!";
$fields = array();
$fields{"Name"} = "Name";
$fields{"Company"} = "Company";
$fields{"Email"} = "Email";
$fields{"Phone"} = "Phone";
$fields{"list"} = "Mailing List";
$fields{"Comments"} = "Comments";
$body = "Soul Watt has received the following information:\n\n";
foreach($fields as $a => $b) {
$body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]);
}
$headers2 = "From: noreply#soulwatt.com";
$subject2 = "Thank you for contacting Soul Watt!";
$autoreply = "Thank you for contacting us. Somebody will get back to you as soon as possible, usualy within 48 hours. If you have any more questions, please consult our website at www.soulwatt.com";
if($from == '') {
print "You have not entered an email. Please enter your email and try again.";
}
else {
if($name == '') {
print "You have not entered a name.<br />Please enter your name and try again.";
}
else {
$send = mail($to, $subject, $body, $headers);
$send2 = mail($from, $subject2, $autoreply, $headers2);
if($send) {
print "<p><span>THANK YOU FOR CONTACTING US!</span></p>";
print "<p><span>Someone will get back to you as soon as possible, usually within 48 hours. If you need immediate assistance regarding booking Soul Watt, please call Randy at (828) 729-3199.</span></p>";
}
else {
print "<p><span>We encountered an error sending your mail, please notify webmaster#soulwatt.com</span></p>";
}
}
}?>
Thanks for your help!
These 2 lines:
$from = $_REQUEST['Email'] ;
if($from == '') {
print "You have not entered an email. Please enter your email and try again.";
}
Mean that you check the email request (POST and GET) key. The first time you load this page this WILL be empty. You could add a check if there was a POST at all, for instance if there was submitted.
To be honest, there might a lot of problems with your code: a user can add all sorts of stuff in there, probably even add stuff in the headers to add 'to' fields and all.. You might be making a spam-machine here. This part: $headers = "From: $from"; just adds the request field FROM in your headers....
You'd want to wrap your validation section in
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... do validation here ...
}
... print form here ...
That will only run the validation code AFTER you submit the form. As it stands now, it's running each time the page is loaded, so of course there's no form data to validate the first time around.
Does your form fields have the same name that you're checking?
I mean for
$from = $_REQUEST['Email'];
You should have
<input type='text' name='Email' /> <!-- Note the Capital E -->
I add my comments here:
Use $_POST or $_GET. Avoid $_REQUEST. That way you've more controll over your app.
Also, don't check emptiness with =="" try empty($from)
OK So if the form is on http://www.soulwatt.com/contact.php and you have
<form method="post" action="contact.php" name="contact_form" id="contact_form">
action="contact.php" : That means it is proccessing the form on the same address so you will see the results of the form processing on the same page, and since the form is empty, and you're checking it regardless of it having been posted or not, you get that error

Categories