So this is my first post, I try to tell what my issue's are.
I have bought a domain name that I want to sell.
So I code a simple HTML website with some CSS stuff.
OK. I also have a form in my HTML, that contains this:
<input type="text" placeholder="Amount" name="amount">
<input type="text" placeholder="Name" required name="name">
<input type="text" placeholder="Email Address" required name="email">
<div class="validation">
<button class="btn" name="submit">Send request</button>
$email_to = "email#email.com";
$amount = $_POST["amount"];
$name = $_POST["name"];
$email = $_POST["email"];
$email_subject = "Domeiname";
$headers = "From: " . $email . "\n";
$headers .= "Reply-To: " . $email . "\n";
ini_set("sendmail", $email);
$sent = mail($email_to, $email_subject, $amount, $headers, "-f" .$email);
if ($sent)
{
header("Location: https:mywebsite.com");
} else {
echo "There has been an error sending your comments. Please try later.";
}l
It's working and I receive emails. So my question is, is it safe? Is it vulnerable to hackers?
(I also receive in my Gmail, that this email can be spam/not from me).
Am I doing something wrong?
EDIT: Found another issue: In my email, I only receive the "amount" status and not the "name + email".
There are a number of libraries that will take all the hard work of securely sending email from you - such as swiftmailer.
<?php
require_once 'lib/swift_required.php';
// Sendmail
$transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance('Wonderful Subject')
->setFrom(array('john#doe.com' => 'John Doe'))
->setTo(array('receiver#domain.org', 'other#domain.org' => 'A name'))
->setBody('Here is the message itself')
;
// Send the message
$result = $mailer->send($message);
You may also find it very valuable to sign up for a service such as Mailgun and also setup your code to use their servers to actually send the email (there are libraries would setup as a 'transport' to send the message to them via HTTP, and then they email it to the final destination). There are a number of such 'ESP' (Email Service Providers), and many offer a substantial free-tier, so it won't cost you anything for even thousands of emails per month.
It looks as though you are sending an E-mail when a form is submitted. This is perfectly secure; there is no way a hacker could manipulate who the E-mail gets sent to; PHP is server-side code. Thus, $email_to = "email#email.com"; cannot get manipulated from the form itself, as it is hard-coded into your PHP.
Obviously, the $_POST data variables get passed through from the form, so their contents can be manipulated by the form -- though this is required in order for you to be able to retrieve the visitor's name and E-mail address.
PHPMailer did have a recent vulnerability in it, where an attacker could breach your website by entering a certain 'From' E-mail address, but this has since been patched. You still need to allow the user to enter their E-mail address, or you won't know who to reply to.
However, a user would still be able to create additional headers based on you not validating that the 'From' address is an actual valid E-mail address. You should validate this, and only send the E-mail if it is found to be valid:
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$sent = mail($email_to, $email_subject, $amount, $headers, "-f" .$email);
}
Note that you're also not actually doing anything with the $name variable. Assuming you're trying to make it display the person's name in the 'FROM' field in the E-mail, you need to pass it as:
$headers = "From: " . $name . " <" . $email . ">\n";
So that it gets rendered as From: Person <email#email.com>.
Hope this helps! :)
Related
I am trying to send email from a web page hosted on a shared platform over at fasthosts. I cannot for the life of me get this to work, I had a much more extensive script which checked the validity of email etc, but now I've been reduced to using the basic example from fasthosts and it is still not working.
Please could someone take a look and let me now where I am going wrong...
<?php
// You only need to modify the following two lines of code to customise your form to mail script.
$email_to = "contact#mywebsite.co.uk"; // Specify the email address you want to send the mail to.
$email_subject = "Feedback from website"; // Set the subject of your email.
// This is the important ini_set command which sets the sendmail_from address, without this the email won't send.
ini_set("contact#mywebsite", $email_from);
// Get the details the user entered into the form
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
// Validate the email address entered by the user
if(!filter_var($email_from, FILTER_VALIDATE_EMAIL)) {
// Invalid email address
die("The email address entered is invalid.");
}
// The code below creates the email headers, so the email appears to be from the email address filled out in the previous form.
// NOTE: The \r\n is the code to use a new line.
$headers = "From: " . $email_from . "\r\n";
$headers .= "Reply-To: " . $email_from . "\r\n"; // (You can change the reply email address here if you want to.)
// Now we can construct the email body which will contain the name and message entered by the user
$message = "Name: ". $name . "\r\nEmail: " . $email . "\r\nMessage: " . $message ;
// Now we can send the mail we've constructed using the mail() function.
// NOTE: You must use the "-f" parameter on Fasthosts' system, without this the email won't send.
$sent = mail($email_to, $email_subject, $message, $headers, "-f" . $email_from);
// If the mail() function above successfully sent the mail, $sent will be true.
if($sent) {
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$name .' Thank you for contacting us.'));
die($output);
} else {
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}
?>
I have a contact form on my website which sends an email to my account and an auto-response to the users who fills the form. I could able to send an auto-reply to non-Gmail accounts but not to Gmail accounts, it's not even sent to spam. I want to know is anything missing in the code, or any settings have to be changed, let me know
code is working fine with non-Gmail accounts
<?php
$email_to = 'mailme#example.com'; //your email
$business = 'company name.,'; //business name
//$topic = $_POST['topic'];
$name = $_POST['name'];
$email_from = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$autoResponse = true; //set to false if you don't want to send an auto reply
$autoResponseSubject = "Demo Contact Form";
$autoResponseMessage = "Hi, thank you for contacting us, we will get back to you soon.";
$autoResponseHeaders = "From: $business <$email_to>\r\n";
$autoResponseHeaders .= "Reply-To: $business <$email_to>\r\n";
$headers = "From: $name <$email_from>\r\n";
$headers .= "Reply-To: $name <$email_from>\r\n";
if(#mail($email_to,$subject, $message, $headers)){
if($autoResponse === true){
mail($email_from, $autoResponseSubject, $autoResponseMessage, $autoResponseHeaders);
}
echo '1';
} else {
echo '0';
}
?>
I am not getting any errors.
Google, Microsoft, and the like, only accept email from mail servers that fulfill a number of requirements. These requirements are changing over time. This has mainly to do with preventing spam.
Things start with SPF, which is rather simple, but the normal site providing documentation has been down since feb 2019. Have a look at Wikipedia instead.
The next thing is DKIM. Without it mail certainly won't been accepted by GMail.
Then there is also DMARC.
After all of this there is still no guarantee that your mail will be accepted. Your IP could be blacklisted.
As you can probably guess by now, running your own mail server is a lot of work. I've stopped doing it years ago. I now use a third party service for this.
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 6 years ago.
I'm attempting to run an email form, which takes text from the user's input forms and send them to my desired email (seen as $myemail in the php below).
<form method="post" name="contact_form" action="Contact.php">
Your Name: <input type="text" required name="name">
Email Address: <input type="text" required name="email">
Message: <textarea required name="message"></textarea>
<input type="submit" value="Submit">
</form>
<?php
$errors = '';
$myemail = 'enterDesiredEmail';
if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message'])) {
$errors .= "\n Error: all fields are required";
}
$name = null;
$email_address = null;
$message = null;
$name = $_POST["name"];
$email_address = $_POST["email"];
$message = $_POST["message"];
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",$email_address)) {
$errors .= "\n Error: Invalid email address";
}
if( empty($errors)) {
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email_address\n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
}
?>
I spat the above code out onto a webpage and uploaded the file to my server. Upon accessing the webpage online, filling in content to the form, and clicking sbmit, the page refreshed with the inputs and textarea clear as expected. When I checked the email I had set, no message was received. What could I do to correct this code so that the desired email address actually receives a message?
Many thanks.
Some pointers that may well solve your issue without specifically telling you what the cause of this issue actually is:
1) Use Error Logging.
2) Check that you have a valid mail server setup on your server. As stated in comments by Jason K.
3) Use a mailing library such as PHPMailer. It sidesteps a huge amount of the headache.
4) Check your emails are valid with the correct code, principly using filter_var rather than obtuse regexes.
Also check emails are Sanitized (FILTER_SANITIZE_EMAIL) as well.
5) If not using or setting up a library such as PHPMailer or SwiftMailer then you need to check your mail headers are exactly correct.
BONUS
There seems to be some conflicting accounts of what to use for email line endings [including headers], but I would suggest PHP_EOL or \r\n (the same thing on Linux servers). \n is not suitable. As stated in comments by Barmar.
Good luck
You should try to use a library such as PHPMailer. Themail() function is sometimes not flexible enough to achieve what you need in most cases. Also the mail() function requires a local mail server. In addition, PHPMailer offers a lot of addons such as the ability to set up attachments or the ability to send HTML emails to your users. Using a library like this also means that you emails will be sent out almost all the time since it it tested and used by a lot of people.
You can find a tutorial for using PHPMailer here: https://www.sitepoint.com/sending-emails-php-phpmailer/
Example code taken from the website using PHPMailer:
<?php
require_once "vendor/autoload.php";
//PHPMailer Object
$mail = new PHPMailer;
//From email address and name
$mail->From = "from#yourdomain.com";
$mail->FromName = "Full Name";
//To address and name
$mail->addAddress("recepient1#example.com", "Recepient Name");
$mail->addAddress("recepient1#example.com"); //Recipient name is optional
//Address to which recipient will reply
$mail->addReplyTo("reply#yourdomain.com", "Reply");
//CC and BCC
$mail->addCC("cc#example.com");
$mail->addBCC("bcc#example.com");
//Send HTML or Plain Text email
$mail->isHTML(true);
$mail->Subject = "Subject Text";
$mail->Body = "<i>Mail body in HTML</i>";
$mail->AltBody = "This is the plain text version of the email content";
if(!$mail->send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent successfully";
}
?>
You need to interpolate the actual $email variable inside the double quote from :
$headers = "From: $myemail\n"; to
$headers = "From: ${myemail}"."\r\n";
If you Specify additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n).
This is an example from php doc:
`<?php
$to = 'nobody#example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>
Happy coding!
I want to send an email with PHP when a user has finished filling in an HTML form and then emailing information from the form. I want to do it from the same script that displays the web page that has the form.
I found this code, but the mail does not send.
<?php
if (isset($_POST['submit'])) {
$to = $_POST['email'];
$subject = $_POST['name'];
$message = getRequestURI();
$from = "zenphoto#example.com";
$headers = "From:" . $from;
if (mail($to, $subject, $message, $headers)) {
echo "Mail Sent.";
}
else {
echo "failed";
}
}
?>
What is the code to send an email in PHP?
EDIT (#1)
If I understand correctly, you wish to have everything in one page and execute it from the same page.
You can use the following code to send mail from a single page, for example index.php or contact.php
The only difference between this one and my original answer is the <form action="" method="post"> where the action has been left blank.
It is better to use header('Location: thank_you.php'); instead of echo in the PHP handler to redirect the user to another page afterwards.
Copy the entire code below into one file.
<?php
if(isset($_POST['submit'])){
$to = "email#example.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
?>
<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>
<form action="" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Original answer
I wasn't quite sure as to what the question was, but am under the impression that a copy of the message is to be sent to the person who filled in the form.
Here is a tested/working copy of an HTML form and PHP handler. This uses the PHP mail() function.
The PHP handler will also send a copy of the message to the person who filled in the form.
You can use two forward slashes // in front of a line of code if you're not going to use it.
For example: // $subject2 = "Copy of your form submission"; will not execute.
HTML FORM:
<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>
<form action="mail_handler.php" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
PHP handler (mail_handler.php)
(Uses info from HTML form and sends the Email)
<?php
if(isset($_POST['submit'])){
$to = "email#example.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
// You can also use header('Location: thank_you.php'); to redirect to another page.
// You cannot use header and echo together. It's one or the other.
}
?>
To send as HTML:
If you wish to send mail as HTML and for both instances, then you will need to create two separate sets of HTML headers with different variable names.
Read the manual on mail() to learn how to send emails as HTML:
http://php.net/manual/en/function.mail.php
Footnotes:
In regards to HTML5
You have to specify the URL of the service that will handle the submitted data, using the action attribute.
As outlined at https://www.w3.org/TR/html5/forms.html under 4.10.1.3 Configuring a form to communicate with a server. For complete information, consult the page.
Therefore, action="" will not work in HTML5.
The proper syntax would be:
action="handler.xxx" or
action="http://www.example.com/handler.xxx".
Note that xxx will be the extension of the type of file used to handle the process. This could be a .php, .cgi, .pl, .jsp file extension etc.
Consult the following Q&A on Stack if sending mail fails:
PHP mail form doesn't complete sending e-mail
PHP script to connect to a SMTP server and send email on Windows 7
Sending an email from PHP in Windows is a bit of a minefield with gotchas and head scratching. I'll try to walk you through one instance where I got it to work on Windows 7 and PHP 5.2.3 under (IIS) Internet Information Services webserver.
I'm assuming you don't want to use any pre-built framework like CodeIgniter or Symfony which contains email sending capability. We'll be sending an email from a standalone PHP file. I acquired this code from under the codeigniter hood (under system/libraries) and modified it so you can just drop in this Email.php file and it should just work.
This should work with newer versions of PHP. But you never know.
Step 1, You need a username/password with an SMTP server:
I'm using the smtp server from smtp.ihostexchange.net which is already created and setup for me. If you don't have this you can't proceed. You should be able to use an email client like thunderbird, evolution, Microsoft Outlook, to specify your smtp server and then be able to send emails through there.
Step 2, Create your Hello World Email file:
I'm assuming you are using IIS. So create a file called index.php under C:\inetpub\wwwroot and put this code in there:
<?php
include("Email.php");
$c = new CI_Email();
$c->from("FromUserName#foobar.com");
$c->to("user_to_receive_email#gmail.com");
$c->subject("Celestial Temple");
$c->message("Dominion reinforcements on the way.");
$c->send();
echo "done";
?>
You should be able to visit this index.php by navigating to localhost/index.php in a browser, it will spew errors because Email.php is missing. But make sure you can at least run it from the browser.
Step 3, Create a file called Email.php:
Create a new file called Email.php under C:\inetpub\wwwroot.
Copy/paste this PHP code into Email.php:
https://github.com/sentientmachine/standalone_php_script_send_email/blob/master/Email.php
Since there are many kinds of smtp servers, you will have to manually fiddle with the settings at the top of Email.php. I've set it up so it automatically works with smtp.ihostexchange.net, but your smtp server might be different.
For example:
Set the smtp_port setting to the port of your smtp server.
Set the smtp_crypto setting to what your smtp server needs.
Set the $newline and $crlf so it's compatible with what your smtp server uses. If you pick wrong, the smtp server may ignore your request without error. I use \r\n, for you maybe \n is required.
The linked code is too long to paste as a stackoverflow answer, If you want to edit it, leave a comment in here or through github and I'll change it.
Step 4, make sure your php.ini has ssl extension enabled:
Find your PHP.ini file and uncomment the
;extension=php_openssl.dll
So it looks like:
extension=php_openssl.dll
Step 5, Run the index.php file you just made in a browser:
You should get the following output:
220 smtp.ihostexchange.net Microsoft ESMTP MAIL Service ready at
Wed, 16 Apr 2014 15:43:58 -0400 250 2.6.0
<534edd7c92761#summitbroadband.com> Queued mail for delivery
lang:email_sent
done
Step 6, check your email, and spam folder:
Visit the email account for user_to_receive_email#gmail.com and you should have received an email. It should arrive within 5 or 10 seconds. If you does not, inspect the errors returned on the page. If that doesn't work, try mashing your face on the keyboard on google while chanting: "working at the grocery store isn't so bad."
If you haven't already, look at your php.ini and make sure the parameters under the [mail function] setting are set correctly to activate the email service. After you can use PHPMailer library and follow the instructions.
You can also use mandrill app to send the mail in php. You will get the API from https://mandrillapp.com/api/docs/index.php.html where you can find the complete details about emails sended and other details.
You need to add an action into your form like:
<form name='form1' method='post' action='<?php echo($_SERVER['PHP_SELF']);'>
<!-- All your input for the form here -->
</form>
Then put your snippet at the top of the document en send the mail. What echo($_SERVER['PHP_SELF']); does is that it sends your information to the top of your script so you could use it.
You need a SMPT Server in order for
... mail($to,$subject,$message,$headers);
to work.
You could try light weight SMTP servers like xmailer
Here are the PHP mail settings I use:
//Mail sending function
$subject = $_POST['name'];
$to = $_POST['email'];
$from = "zenphoto#example.com";
//data
$msg = "Your MSG <br>\n";
//Headers
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "From: <".$from. ">" ;
mail($to,$subject,$msg,$headers);
echo "Mail Sent.";
I think one error in the original code might have been that it had:
$message = echo getRequestURI();
instead of:
$message = getRequestURI();
(The code has since been edited though.)
I have been looking at this for hours now, and I can't figure out why this won't work. I'm trying to send an email using the mail function. For some reason this page works when hosted by iPage, but not by Godaddy. What is the reason for this?
The PHP:
<?php
// Run code if button pressed
if (isset($_POST['submit'])) {
// Makes sure all fields are filled
if (!$_POST['name'] | !$_POST['email'] | !$_POST['message'] ) {
?><script>alert('You forgot to fill in a field');window.location = "http://example.com/contact.php";</script>
<?php
exit;
}
// From the form
$name = trim(strip_tags($_POST['name']));
$email = trim(strip_tags($_POST['email']));
$message = htmlentities($_POST['message']);
$to = 'email#gmail.com';
$subject = "Contact form submitted!";
$body = <<<HTML
$message
HTML;
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
// send the email
mail($to, $subject, $body, $headers);
?><script>alert('Thanks! I will try to get back to you as soon as possible.');window.location = "http://example.com/contact.php";</script><?php
}
?>
You need to look at your if condition you need || to do a OR
<?php
// Run code if button pressed
if (isset($_POST['submit'])) {
// Makes sure all fields are filled
if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message']) ) {
?>
<script>alert('You forgot to fill in a field');
window.location = "http://example.com/contact.php";
</script>
<?php
exit;
}
You are setting From email id $email from user Input, that means its not configured at your server, add a Reply-To header to $email
$headers = "From: youremail#yourdomain.com \r\n";
$headers .= 'Reply-To: '.$email. "\r\n" .
$headers .= "Content-type: text/html\r\n";
Final note, I would suggest you to use Swift Mailer or PHP Mailer to make it simple
For people having trouble sending email on GoDaddy's servers, here's whats going on:
To prevent spam, GoDaddy's servers refuse to send your mail if your using a certain domain (see below for the list). So to solve the specific problem here, I had to change the domain I was using, so $to = 'email#gmail'; is now $to = 'email#something-else.com';
Here is GoDaddy's explanation and the list of blacklisted domains:
Forms are popular on websites; they let customers share their information with you, whether it’s for a newsletter or to register an account. Often times, these forms email a confirmation of the visitor’s submission to to you or the visitor submitting the information. Did you know that all email, even if it’s sent from a hosting account, must have information entered in the From value, though?
You can make that From value a particular email address, too. This lets you create a professional-looking email for your customers or something that’s easy to categorize for yourself.
However, we have to be careful with what users can specify as their From value to combat spamming attempts. Here’s a list of email address domain names we don’t let our customers use as the From value of their forms:
gmail.com
aol.com
aim.com
yahoo.com
hotmail.com
live.com
msn.com
If your email form uses one of these domain names for its From email address, our server will not send the email.