Html/php email send [duplicate] - php

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 6 years ago.
I am about to write a little html/php script. But I am not able to send data from the HTML form input to any email address or into any text file. I was already searching for possible solutions but nothing worked for me. The Browser replayed the php script. But no mail has been send. Any help will be appreciated. Thank you.

I recommend you use PHPMailer his use is very easy

Do not forget the action and method attributes in the <form> tag.
contents of html file
<form action="send.php" method="POST">
<input type="text" name="name" placeholder="Typ your name..." />
<input type="email" name="from" placeholder="Typ your e-mailaddress..." />
<textarea name="message" placeholder="Typ your message..."></textarea>
<button type="submit">Send E-mail</button>
</form>
contents of send.php
<?
if(isset($_POST)) {
$name = $_POST['name'];
$message = $_POST['message'];
$from = $_POSST['from'];
if(!empty($name) && !empty($message) {
$subject = 'message from '.$name;
$headers = "From: " . strip_tags($from) . "\r\n";
$headers .= "Reply-To: ". strip_tags($from) . "\r\n";
//$headers .= "CC: susan#example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
// #SEE: http://php.net/manual/en/function.mail.php
if(mail('[YOUR-ADDRESS]', $subject, $message, $headers)) {
echo 'Thx 4 msg!';
}
else {
echo 'Oh nooos, The msg was not send.';
}
}
else {
echo 'You should provide the fields with some data..';
}
}
?>
One should first sanitize the user input obviously.

I think your issue is how to handle form data with some code, so you may be able to send an email or write form data to a file. This is where you see the difference between client-side and server-side. HTML is a language to describe documents, here your form: the text input name is going to describe a name, the form will send its data within the POST method, and so on. The file describing HTML is processed in your browser. And your browser don't send an email or write data... That's why you should use a server-side language such as PHP to get things done. PHP is great to help you process data and behave on different event... In your case, great for receiving data, analyze data and then send data through mails or save data into a file.
So now you may want to understand how to do so... Mail are a little tricky since you may need to configure things such as mail server, authentification and so one. Maybe a good solution is to try mails with a Google account or something like that... When it will be done, you may simply send an email like so:
<?php
$to = 'your#email.here';
$subject = 'Mail test';
$data = $_POST['name']; // if a `name` field exist and your form send its data through POST method
mail($to, $subject, $data);
Writing things to a file is simpler, it only request permissions to read and/or write a file.
<?php
$file = 'path/to/file';
file_put_contents($file, $_POST['name'] . ' for example');
So this is globally everything:
index.html HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Form</title>
</head>
<body>
<form action="process.php" method="post">
<input name="name" type="text" placeholder="Name" />
<input type="submit" value="Process">
</form>
</body>
</html>
and process.php PHP file
<?php
/**
* Testing data
*/
if (!isset($_POST['name'])) {
die('No value `name` found');
}
/**
* Configuring process
*/
$to = 'your#email.here';
$subject = 'Mail test';
$data = $_POST['name'];
/**
* Saving data
*/
$res = file_put_contents(
'data.txt',
$data."\r\n"
);
if ($res !== false) {
echo 'data saved'.PHP_EOL;
} else {
echo 'error while saving data'.PHP_EOL;
}
/**
* Sending email
*/
$res = mail(
$to,
$subject,
$data
);
if ($res === true) {
echo 'mail sent';
} else {
echo 'error while sending mail'.PHP_EOL;
}
I suggest you to read mail() and file_put_contents() documentations to understand their behavior in case there are errors... :)

Related

Trying to get an Email to send on button click, but it keeps displaying an Error [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 2 years ago.
I'm working on a project that requires a specific button on a page to send an email out. It works as a sort of reminder function for the client, so when it's clicked they will receive an email to let them know that they need to check something.
I think I almost have it working, but for some reason it keeps failing instead of actually sending the email out. It could be the way that I have it set out, but I have tried using the "action" on the form to run the php through a seperate file, but it still does the same. I currently have it like this:
<form method='post'>
<button type='submit' name='reminder_btn'>
Send Reminder
</button>
</form>
<?php
if(isset($_POST['reminder_btn'])){
$email = "hello#email.com";
$subject = "Company Reminder";
$message = "
<html>
<head>
<title>Company</title>
</head>
<body>
<p>Hello!</p>
<p>You have a reminder. Please check the website.</p>
<p>Thanks!</p>
</body>
</html>
";
$mailheaders[] = "From: Company Name";
$mailheaders[] = "Reply-To: hello#email.com";
$mailheaders[] = "MIME-Version: 1.0";
$mailheaders[] = "Content-type: text/html; charset=iso-8859-1";
if(mail($email, $subject, $message, implode("\r\n", $mailheaders))) {
echo "Reminder sent.";
} else {
echo "Something has gone wrong. Try again.";
}
}
I'm sure I've had it working like this on something else before, but all I'm getting is the "Something has gone wrong" message each time.
Obviously I've got something wrong but I don't understand what it is, so any assistance here would be much appreciated.
You forgot the action on the form. I have used PHP SELF but you can replace it with your page. PHP SELF sends the POST data to the same page.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method='post'>
<button type='submit' name='reminder_btn'>
Send Reminder
</button>

How do I validate my email submission on php?

I'm just getting into coding and put together a webpage using dreamweaver. I created a php page with my email coding which is executed from a form and submit button on an html page. I continously recieve blank emails on a daily basis which apparently means I need to add validation coding. I tried adding the coding but the problem persists. The page still submits even if the form is blank.
Below is my current coding.
<?php
if(!filter_var($_POST['CustomerEmail'], FILTER_VALIDATE_EMAIL)) { $valerrors[] = "The email address you supplied is invalid." ;}
$customeremail=$_POST['CustomerEmail'];
$email='test#gmail.com';
$custfirst=$_POST['CustomerFirstName'];
$custlast=$_POST['CustomerLastName'];
$custphone=$_POST['CustomerNumber'];
$custaddress=$_POST['CustomerAddress'];
$custcity=$_POST['CustomerCity'];
$custstate=$_POST['CustomerState'];
$custrequest=$_POST['CustomerService'];
$subject='Service Request';
$body = <<<EOD
<br><hr><br>
Email: $customeremail <br>
First Name: $custfirst <br>
Last Name: $custlast <br>
Phone: $custphone <br>
Address: $custaddress <br>
City: $custcity <br>
State: $custstate <br>
Request: $custrequest <br>
EOD;
$headers = "From: $customeremail\r\n";
$headers .= "Content-type: text/html\r\n";
$Send = mail($email, $subject, $body, $headers);
$confirmation = <<<EOD
<html>"Thanks for Submitting."</html>
EOD;
echo"$confirmation";
?>
It's possible that I'm placing the if statement in the wrong place. Can someone correct my coding so the confirmation page will not load and the email will not be sent if the customer email is left blank?
You need to check like this
if (filter_var('abc#gmail.com', FILTER_VALIDATE_EMAIL)) {
echo 'VALID';
} else {
echo 'NOT VALID';
}
see here : http://php.net/manual/en/function.filter-var.php
You could initialize $valerrors = []; at the beginning and use a condition such as:
if (empty($valerrors)) {
$headers = "From: $customeremail\r\n";
$headers .= "Content-type: text/html\r\n";
$Send = mail($email, $subject, $body, $headers);
$confirmation = <<<EOD
<html>"Thanks for Submitting."</html>
EOD;
}
Note that you should apply similar validation to all user inputs.
I think u can add "required" attribute to your email input in your form Html
<input type="email" name="CustomerEmail" required>
So Html wont allow you to submit until you provide a value

Does PHP 5.x mail() verify validity of domains in"reply-to" fields?

I've recently been "prettifying" some tried and true email forms to make them more mobile friendly, and thought I was going out of my mind seeing the PHP mail() function now randomly failing (and returning FALSE). Well it wasn't random. After nearly pulling out all my hair, I finally realized that anytime I entered an invalid domain for the form field that becomes my "reply-to" address, mail() would fail, and return FALSE! Note, these aren't "malformed" email addresses (which i already check for), just invalid ones (like "name#goooogle.com").
I've included a test form code below if you think it matters, but do you think this is a new "feature" of PHP, or something that just my hosting company's server is doing? If it is PHP, is there maybe some new "testDomain()" function I could also add to my forms? It would be nice to alert the user who made a legitimate mistake, but all I can tell them for sure is that their mail attempt failed. After all, mail() doesn't return some friendly little error code that indicates what happened, it just returns true or false. In fact when it does return false, it doesn't even report an error in the log file.
Truth be told, this is the ONLY time I've ever gotten mail() to fail in my forms. But I think assuming the failure always meant the domain was bad would be unwise.
<!DOCTYPE HTML>
<html>
<head> <title> Simple Test Email Form;</title> </head>
<!--
<?php
// define variables and set to empty values
$name = $email = $comments = ""; // $address = $citystate = $zip = $phone not used
$nameErr = $emailErr = $commentsErr = "";
$headers = $email_message = $sendersIP = "";
$email_to = "myaddress#mydomain.org"; // this is bogus!!!
$email_subject = "Private Mailform";
$status = "Form Not Yet Processed";
// some basic security functions
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// mail processing
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"])) { $nameErr = " Name is required"; }
else { $name = test_input($_POST["name"]); }
if (empty($_POST["email"])) { $emailErr = "Email is required"; }
else { $email = test_input($_POST["email"]); }
// at least email should be validated
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)) { $emailErr = "Invalid email format"; }
// keep senders IP, so we can watch for idiots.
$sendersIP = $_SERVER['REMOTE_ADDR'];
$comments = $_POST["comments"];
// So is all well?
if (empty($nameErr) && empty($emailErr) && empty($commentsErr) )
{
$email_message = $headers = "";
$email_message .= "Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email)."\n";
$email_message .= "IP: ".$sendersIP."\n";
$email_message .= "Comments: "."\n\n".clean_string($comments)."\n";
// create regular email headers
$headers .= 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
'X-Mailer: PHP/' . phpversion();
$mail_sent = mail($email_to, $email_subject, $email_message, $headers);
// modify status string to show result
$status = ($mail_sent==TRUE) ? "mail() function returned TRUE" :" mail() function returned FALSE";
}
}
?>
-->
<body >
<table><tr><td style ="text-align:right;" width=100%>
<b><?php echo $status; ?></b><br>
<p><span >* = required fields.<br>Please double check your email address.</span></p>
<form name="contactform" method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <span class="error">*<?php echo $nameErr;?></span>
<input type="text" name="name" value="<?php echo $name;?>"><br>
Email: <span class="error">*<?php echo $emailErr;?></span>
<input type="text" name="email" value="<?php echo $email;?>"><br>
<br>
<div align="center"> ---- <span class="error">*</span> Message ---- <span class="error"><?php echo $commentsErr;?></span><br>
<textarea name="comments" wrap="physical" cols="40" rows="10" ><?php echo $comments;?></textarea>
<br><br>
</div>
<input name="submit" id="submit" type="submit" value="Submit" >
</form>
</td></tr></table>
</body>
</html>
mail has no native checks for validity. Vanilla sendmail doesn't either. So it's possible your host has their MTA client doing this. You might be able to test this using a separate mail client. For instance, ZF2, PHPMailer and many other modern PHP mailing systems don't use the mail function at all. They actually open a socket and send the mail commands directly. It's not easy, but you could tinker with this to send you back the actual commands and responses and see where the SMTP transaction is failing.
You can add your own validation before it gets that far, incidentally.
// this will fail to send if the DNS for the domain has no MX records
if(!checkdnsrr($domain, 'MX')) {
// don't send
}
No. mail() is not for that. It may be that SMTP you are using would do that, but that depends on the setup of said server.
PS: do not use mail(). It is very primitive. Use phpmailer or other tools to make mail sending easier

Few PHP script E-Mails Not getting delivered

I have created folders under my domain.
Emails scripts in folder-1 are getting delivered but scripts in folder-2 show message = "email sent successfully". But these emails are not receiving in email address.
I am using phpmailer
When this sampleemail.php file is kept in Folder1, Email get delivered. But when same file is kept in Folder2, Error Message is there.
Code is as follows :
<?
$msg="";
if(isset($_POST['submit']))
{
$from_add = "name#my-web-site.com";
$to_add = "myemail#gmail.com"; //<-- put your yahoo/gmail email address here
$subject = "Test Subject";
$message = "Test Message";
$headers = "From: $from_add \r\n";
$headers .= "Reply-To: $from_add \r\n";
$headers .= "Return-Path: $from_add\r\n";
$headers .= "X-Mailer: PHP \r\n";
if(mail($to_add,$subject,$message,$headers))
{
$msg = "Mail sent OK";
}
else
{
$msg = "Error sending email!";
}
}
?>
And HTML Sample Form As Follows :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Test form to email</title>
</head>
<body>
<?php echo $msg ?>
<p>
<form action='<?php echo htmlentities($_SERVER['PHP_SELF']); ?>' method='post'>
<input type='submit' name='submit' value='Submit'>
</form>
</p>
</body>
</html>
I would suggest you use PHPmailer because it has the function which you needed. The reason i am not suggest you use your method because it need to change the sendmail() function in your localhost.
For example: if u using xampp, you must go into the sendmail directory and go for sendmail.php to edit the SMTP to mail.google.com and so on.
Please try this tutorial:
http://codeforgeek.com/2014/11/phpmailer-ultimate-tutorial/
Hope it can helps you.
Looking at your code I see you are NOT using "PHPMailer", but "PHP's mailer".
Regarding your problem of undelivered emails and error message, here are some general hints:
If you send HTML mail, always send a multipart email containing both, HTML and TEXT
Don't use "X-Mailer: PHP". There are mail servers who will give your mail an increased spam score just because of that.
If you get an error, try this:
$errLevel = error_reporting(E_ALL ^ E_NOTICE);
mail(...);
error_reporting($errLevel);
Try using a different delivery method (smpt, sendmail, ...)

PHP/Wordpress - Trying to mail an order form

I have a rather large form built, and unfortunately my friend is using WordPress. After much research of how to get PHP to run on an individual page, I created a custom template for the page and inserted my PHP which is to read that it was a post, and send a wp_email accordingly.
My form starts out:
<form name="healthyOrderForm" method="POST" action="/order-sent" enctype="text/plain">
the /order-sent does send it to the correct page as I can see my php response when it gets there.
Form submit button is:
<input type="submit" name="send" value="Submit Order" />
PHP is:
<?php
if (isset($_POST['submit'])) {
$to = 'testemail#gmail.com';
$subject = 'New Healthy Order';
$message .= 'Location: ' . $_POST['location'] ;
$headers = "From: randomemail#gmail.com\r\n";
$headers .= 'Content-Type: text/plain; charset=utf-8';
$success = wp_mail( $to, $subject, $message, $headers);
}
?>
Any help would be greatly appreciated as I have been stuck on this for over 24 hours now.
You have no $_POST['submit']. The name of your submit is $_POST["send"]. Check on that.
EDIT
And, as Fred-ii- pointed me to that, remove the enctype="text/plain" from your form tag.

Categories