PHP form > PHP forms tutorial >
Form to mail
Sending form results to your e-mail address
Sending e-mails in PHP is quite trivial, all you need to do is
use the mail() function. The syntax is:
mail(RECIPIENT, SUBJECT, MESSAGE [, HEADERS]);
|
First three parameters are required, headers are optional. Here is
an example to make things more clear. If you want to send an e-mail
with subject "Test e-mail" and message "Hi, this is a test message!"
to address "john@doe.com" the code would look like:
mail("john@doe.com", "Test e-mail", "Hi, this is a test message!");
|
It is usually more practical to store recipient, subject and message
in variables then typing them directly inside mail(). This is especially
true if you have a long subject and message.
Also when you are sending e-mail don't forget to display
a response confirming the form has been submitted ("thank you"
page).
<?php
$recipient = "you@yourdomain.com";
$subject = "This is a test e-mail";
$message = "Hi!
This is a test message (e-mail body).
This is a new line
Enough for now.
Best regards,
Test test
";
mail($recipient, $subject, $message);
?>
<html>
<body>
Your message was successfully sent!<br />
<br />
Thank you for contacting us!
</body>
</html>
|
Instead of printing the response HTML code you can create a
separate thank you page ("thank_you.html") and redirect
the visitor after mail() by printing a 'Location:' header:
header('Location:thank_you.html');
|
...or use the full URL to thank_you.html:
header('Location:http://www.domain.com/thank_you.html');
|
So the above code would look like:
<?php
$recipient = "you@yourdomain.com";
$subject = "This is a test e-mail";
$message = "Hi!
This is a test message (e-mail body).
This is a new line
Enough for now.
Best regards,
Test test
";
mail($recipient, $subject, $message);
header('Location:thank_you.html');
?>
|
On the next page we will put everything we learned together
and create the final version of our contact form.
» Copyright notice
© 2008-2024 myPHPform.com. All rights reserved. Copying or redistributing
any part of this website without our written permission is expressly
forbidden!
|