DEV Community

Sidra Maqbool
Sidra Maqbool

Posted on

How to Send an HTML Form to Email Using PHP: A Step-by-Step Guide with Code Examples


If you have a website with an HTML form that collects user data and you want to receive this data via email, you can use PHP to achieve this. Here's how to do it:

  1. Create an HTML form with input fields for the data you want to collect, such as name, email, phone, and message. Make sure to use the "method" attribute of the form tag to specify "POST" so that the form data is submitted via the HTTP POST method.

  2. Create a PHP script that will receive the form data and send it to your email address. The PHP script should retrieve the form data from the $_POST superglobal array, set the email headers, and use the mail() function to send the email.

  3. In the PHP script, use the $_POST superglobal array to retrieve the values of the input fields in the form. For example, to retrieve the value of the "name" field, use $_POST['name'].

  4. Set the recipient email address, sender name and email address, email subject, and message body using variables. For example, you can set the recipient email address using $to = 'your_email@example.com';, and the sender name and email address using $headers = 'From: ' . $name . ' <' . $email . '>';.

  5. Use the mail() function to send the email. For example, you can use mail($to, $subject, $message, $headers); to send the email.

To display a confirmation message to the user after the email is sent, you can output a message using the echo statement. For example, you can use echo 'Your message has been sent successfully!';.

That's it! With these steps, you can easily send an HTML form to email using PHP. Keep in mind that this is a basic example and you may need to modify the code to suit your specific requirements. Happy coding!

Top comments (0)