Home > Backend Development > PHP Tutorial > How to Send an Email with PHP from an HTML Form Using the Same Script?

How to Send an Email with PHP from an HTML Form Using the Same Script?

Linda Hamilton
Release: 2024-12-20 03:37:12
Original
976 people have browsed it

How to Send an Email with PHP from an HTML Form Using the Same Script?

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

Q > I want to send an email with PHP from an HTML form, using the same script that displays the form.

A > To achieve this, consider the following solution:

PHP Code:

if (isset($_POST['submit'])) {
    $to = $_POST['email'];
    $subject = $_POST['name'];
    $message = getRequestURI();
    $from = "[email protected]";
    $headers = "From:" . $from;

    if (mail($to, $subject, $message, $headers)) {
        echo "Mail sent.";
    }
    else {
        echo "Failed to send mail.";
    }
}
Copy after login

HTML Form:

<form method="post">
    <label>Name:</label>
    <input type="text" name="name">

    <label>Email:</label>
    <input type="email" name="email">

    <input type="submit" name="submit" value="Send">
</form>
Copy after login

In this code, when the form is submitted, the PHP script is executed. It retrieves the submitted information, crafts the email, and sends it using the mail() function. The result is displayed on the same page.

The above is the detailed content of How to Send an Email with PHP from an HTML Form Using the Same Script?. 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