Send Email With PHP From Html Form On Submit With The Same Script

To send an email with PHP from an HTML form on submit using the same script, you can follow these steps:

  1. Create an HTML form with the necessary input fields for the sender’s name, email, subject, and message. Set the form action to the current PHP script itself using $_SERVER['PHP_SELF'] as the action attribute value. For example:
  1. In the same PHP script, check if the form has been submitted. Use the isset() function to check if the $_POST['submit'] variable is set. If the form is submitted, process the form data and send the email. For example:
    // Get form data
    $name = $_POST['name'];
    $email = $_POST['email'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];

    // Construct the email headers
    $headers = "From: $name <$email>" . "\r\n";
    $headers .= "Reply-To: $email" . "\r\n";
    $headers .= "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

    // Send the email
    $to = "[email protected]"; // Change this to the recipient's email address
    $mail_sent = mail($to, $subject, $message, $headers);

    // Check if the email was sent successfully
    if ($mail_sent) {
        echo "Email sent successfully.";
    } else {
        echo "Failed to send email.";

Make sure to change the [email protected] email address in the $to variable to the actual recipient’s email address.

Note that the mail() function in PHP may require some additional server configuration to properly send emails. Alternatively, you can use third-party email libraries like PHPMailer or SwiftMailer for more advanced email functionalities.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!