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

[ad name=”In Post”]
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.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.