php

How to Send HTML Form Data to Email Using PHP

Last updated: 21.02.2026
Views: 156

Sending a form to email is an important and common way of communicating with a web resource user. Let’s write a simple form for sending data to email using the PHP mail() function. Our form will also write data to a file on the server. The code is not tied to any CMS and can be used anywhere. It is important that the mail() function is enabled on your hosting.

<?php 
if(isset($_POST['spam']) && isset($_POST['submit']) && !$_POST['spam']){
 
    //departure date
    $date = date('d-m-Y H:i');
    //the value from the name field is limited to 100 characters
    $field_name = substr(htmlspecialchars(trim($_POST['name'])), 0, 100);
    //the value of the message field is limited to 1000 characters
    $field_message = substr(htmlspecialchars(trim($_POST['message'])), 0, 1000);
 
    $to = "user@example.com"; //to
    $subject = "Data from the feedback form";
    //text of the letter
    $msg = "Name: $field_name
    \nMessage: $field_message";
 
    $headers = 'From: webmaster@example.com'; // from
 
    mail($to, $subject, $msg, $headers);//send the letter
 
    //create a string to write to the file on the server
    $file_msg = "$date Name: $field_name; Message: $field_message;\n";
 
    //write data to file
    file_put_contents(__DIR__ . '/mail.txt', $file_msg, FILE_APPEND); 
 
    echo '<p>Thank you for your message</p>';
}
 
?>
<form method="post" action="">
    <input type="text" name="name" placeholder="Name*" required>
    <textarea name="message" placeholder="Message*" required></textarea>
    <input type="hidden" name="spam" value="">
    <input type="submit" value="Send" name="submit">
</form>

We send a letter to user@example.com. In the “from” value, it is desirable to specify a mailbox from the current domain. The data is written to the mail.txt file. The fields in the form were set as mandatory using the “required” attribute. The “spam” field will provide protection from spambots, but minimal. The form handler is at the current address. We display a thank-you message after successful sending.

In your implementation, you can save the data to the database instead of writing it to the file. You can also move the request handler to a separate file.

author
Author: Igor Rybalko
I have been working as a front-end developer since 2014. My main technology stack is Vue.js and WordPress.

Similar posts:

Leave a Reply

Your email address will not be published. Required fields are marked *