Simple PHP Script to Send Email with Mail()

Dzhuneyt Ahmed - Author of this post
Dzhuneyt Ahmed

Posted · 1 min read

Outdated: This post uses PHP's basic mail() function with no input validation or CSRF protection. For modern PHP email, consider using a library like Symfony Mailer or PHPMailer, which handle SMTP authentication, HTML emails, and security out of the box.

Simple PHP Script to Send Email with Mail()

There are three requirements for sending email through a PHP script: A form, an email processing script, and PHP’s mail() function to be enabled (most hosts have this enabled, but some shared hosts don’t).

Place this inside a file called mail.html

Your Message

The email processing script should be inside a file called mail.php:

if(!isset($_POST['receiver'], $_POST['sender'], $_POST['subject'], $_POST['message'])) die("Error sending email"); // check if the page is tried to be accessed directly (e.g. a hacking attempt)

$to = $_POST['receiver']; $from = $_POST['sender']; $subject = $_POST['subject']; $message = $_POST['message'];

$headers = "From: " . $from . "rn" . "Reply-To: " . $from . "rn" . "X-Mailer: PHP/" . phpversion();

$send = mail($to, $subject, $message, $headers);

You should take into account that this is the simplest form of the email sending script. Security measures have not been implemented, such as email validation, message filtering for harmful code (e.g. javascript injection). If you are going to use this script for a fairly popular project, I recommend that you implement some variable validation and even a captcha to avoid spam. If there is enough interest, I could make some more tutorials on those in the future.

Dzhuneyt Ahmed

Dzhuneyt

Helping teams build reliable cloud infrastructure — without the bloated bill.

Social

My Other Blogs

© 2026 Dzhuneyt Ahmed. All rights reserved.