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.)
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 8 years ago.
The form is submitting and sending the email successfully, but the page not redirecting to google. What am I doing wrong?
<?php
$to = "test#gmail.com";
$email_title = "test from email";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = ($_POST["name"]);
$email = ($_POST["email"]);
$message = ($_POST["message"]);
$info = " Name: $name \r\n Email: $email";
if(mail($to, $email_title, $message, $info)){
header('Location: http://www.google.com/');
}
else {
echo "there is an error";
}
}
?>
Without knowing more (for example, what the actual error looks like or what actually happens in the browser), I can only speculate. Headers can only be sent before any data is sent to the browser. My best guess is something somewhere is sending data down to the browser before the header() call, which therefore negates the header redirect.
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 8 years ago.
I'm trying redirect users to a thank you page after submitting a form but my header location doesn't seem to work (local or online). Nothing happens when clicking the submit button (the email is sent though).
My php looks like this :
<?php
$val= $_POST['val'];
$toemail='mail#mail.com';
$name = $val['name'];
$societe = $val['societe'];
$email = $val['email'];
$phone = $val['phone'];
$msg = $val['msg'];
$subject = 'Contact';
$headers = "From: $email \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=utf-8\r\n";
$message = "<b>Nom : </b>".$name."<br>";
$message .='<b>Societe : </b>'.$societe."<br>";
$message .='<b>Email : </b>'.$email."<br>";
$message .='<b>Telephone : </b>'.$phone."<br>";
$message .='<b>Message : </b>'.$msg;
mail($toemail, $subject, $message, $headers);
header("Location: http://example.com/thankyou.html");
?>
What am I doing wrong? Thanks in advance for your help.
Edit: Thanks for your help. If I turn error reporting I get:
Warning : Cannot modify header information - headers already sent by (output started at /path/email.php:12)
As others have mentioned, the script is sending output before attempting to send the header.
The simplest way to fix it is probably to buffer the output of email() and then send the header, as follows:
ob_start();
mail($toemail, $subject, $message, $headers);
ob_end_clean();
header("Location: http://example.com/thankyou.html");
Problem is, you are sending output before redirect.
Either use output buffering or do it on a new page.
http://ee1.php.net/manual/en/ref.outcontrol.php
very simple use following method
ob_start();
exit(header("Location: http://example.com/thankyou.html"));
Functions that send/modify HTTP headers must be invoked before any output is made. Otherwise the call fails.
Using header() you can redirect only to a page within the same site.
you can try using
header("Location: /thankyou.html");
Hope it helps.
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I know that this question has been asked many times, however, I can't seem to find solutions that are relevant to my situation, since they mostly deal with wordpress.
Here is my mail form:
<?php
$to = "email#gmail.com" ;
$from = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$headers = "From: $from";
$subject = "Contact Submission From domain.com";
$fields = array();
$fields{"name"} = "name";
$fields{"title"} = "title";
$fields{"email"} = "email";
$fields{"phone"} = "phone";
$fields{"prefer_phone"} = "pref_phone";
$fields{"prefer_email"} = "pref_email";
$fields{"message"} = "message";
$fields{"referral"} = "referral";
$body = "Here is their submitted message:\n\n"; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n\n",$b,$_REQUEST[$a]); }
if($from == '') {print "You have not entered an email, please hit back and resubmit";}
else {
$send = mail($to, $subject, $body, $headers);
if($send)
{header( "Location: http://www.domain.com/sent.html" );}
else
{print "We encountered an error sending your mail, please notify support#domain.com";}
}
?>
The email sends just fine, but I get the titular error for the redirect:
Warning: Cannot modify header information - headers already sent by (output started at /home/wills5/public_html/send_henry.php:1) in /home/wills5/public_html/send_email.php on line 23
Edit: It was frickin' whitespace before line 1 apparently, thanks guys.
If the message says the error is in line 1, then it is typically leading whitespace, text >or HTML before the opening
Chances are you have whitespace besides or above your <?php tag, or HTML or some other type of "output". Maybe even a byte order mark.
<?php
echo "Correct";
// or vvv, but not with echo
// header("Location: http://www.example.com/");
?>
(space)
(space) <?php
echo "Incorrect";
header("Location: http://www.example.com/");
?>
<div align="center">Text</div>
<?php
echo "Incorrect";
header("Location: http://www.example.com/");
?>
Footnote: As per Gavin's suggestion, and I quote: "It is good form to leave off the closing php tag on class files for this reason. It prevents the inadvertent inclusion of white-space after an included file."
I don't know a thing about php but with little help and research I managed to set up working contact form with Swift Mailer. It's sending messages alright but I want it to redirect people, after sending message, to thank_you.html page. I tried everything I could but it does not work. Could you help me? Here is the code:
<?php
include("Swift/lib/swift_required.php");
$host = 'xxxxxx.xxxxxx#gmail.com';
$password = 'xxxxx';
$subject = "zapytanie ze strony";
$body = "Zglaszajacy: ".$_POST["fullname"]."\r\n";
$body .= "Telefon: ".$_POST["phone"]."\r\n";
$body .= "E-mail: ".$_POST["email"]."\r\n";
$body .= "Tresc: ".$_POST["description"]."\r\n";
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
->setUsername($host)
->setPassword($password);
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance($subject)
->setFrom(array($host => 'Klient'))
->setTo(array('xxxxxxx#xxxx.gmail.com'=> 'xxxxxx'))
->setBody($body);
$result = $mailer->send($message);
if ($result)
{
header('Location: http://www.xxxxx.org/thank_you.html');
}
echo $result;
?>
I added that part myself:
if ($result)
{
header('Location: http://www.xxxxx.org/thank_you.html');
}
and it does not work. Mail is sent but nothing is happening with form. It just stays there. Please treat me like a total layman in this one ;)
From the php documentation for header():
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called. The same problem
exists when using a single PHP/HTML file.
It's likely that some whitespace is being output either by your code or the included swift mailer code before reaching your call to header.
Try using ob_start() at the start of your code, then ob_end_flush() at the end.