Home > Backend Development > PHP Tutorial > How Can I Send an Email from an HTML Form Using PHP?

How Can I Send an Email from an HTML Form Using PHP?

Patricia Arquette
Release: 2024-12-14 22:58:12
Original
102 people have browsed it

How Can I Send an Email from an HTML Form Using PHP?

Send an Email with PHP from an HTML Form on Submit with the Same Script

Introduction

When a user submits an HTML form, a PHP script can be used to process the form data and send an email. However, some users encounter issues with the mail function not sending the email even when the script runs without errors.

Understanding the Problem

The provided code snippet fails to send an email due to a missing significant parameter in the mail() function. The correct syntax should include the recipient's email address, the email subject, the message content, and the email headers.

Revisiting the Code

Here is a revised version of the PHP script that will send an email from a form:

<?php
if (isset($_POST['submit'])) {
    // Extract data from the form
    $to = $_POST['email'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];
    $headers = "From: " . $from;

    // Send the email using the PHP mail() function
    if (mail($to, $subject, $message, $headers)) {
        echo "Mail Sent.";
    } else {
        echo "An error occurred while sending the email.";
    }
}
?>
Copy after login

HTML Form

Here is the HTML form for which the PHP script will process the data:

<form action="" method="post">
    <label for="email">Email:</label>
    <input type="email" name="email">
Copy after login

Explanation

  • When the form is submitted, the PHP script processes the form data.
  • The mail() function is called with the necessary parameters, and if the email is sent successfully, a message is displayed.
  • If the email cannot be sent, an error message is displayed.

Additional Notes

  • For this code to work, you may need to configure your PHP installation to enable the mail() function.
  • If you encounter any issues or have further questions, please refer to the PHP manual for the [mail function](https://www.php.net/manual/en/function.mail.php).

The above is the detailed content of How Can I Send an Email from an HTML Form Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template