PHP Send Mail

Almost every website sends emails: a contact form message, a welcome email or a password reset link. PHP has a built-in mail() function to send an email directly from your script. This chapter shows how to use it safely, and when to use a library like PHPMailer instead.


Syntax of mail()

mail(
    string $to,
    string $subject,
    string $message,
    array|string $additional_headers = [],
    string $additional_params = ""
): bool
ParameterDescription
toRequired. The receiver of the email
subjectRequired. The subject of the email
messageRequired. The body of the email
additional_headersOptional. Extra headers like From, Cc, Bcc and Reply-To. An array is supported from PHP 7.2
additional_paramsOptional. Extra options for the sendmail program

mail() returns true if the email was accepted for delivery. It does not mean that the email reached the inbox. Full details and more examples are in PHP mail() Function.


Example: send a simple email

<?php
$to = "student@example.com";
$subject = "Welcome to Tutorials Class";
$message = "Hello, thanks for joining us.";
$headers = ["From" => "hello@yourdomain.com"];

if (mail($to, $subject, $message, $headers)) {
    echo "Email accepted for delivery.";
} else {
    echo "Email sending failed.";
}
?>

Output:

Output when a mail server is configured

Email accepted for delivery.


Example: contact form

This is the most common use. The script checks the data first. Never put raw user input in the email headers, because a bad user can add new lines and send spam from your server (header injection). Here the email is validated with filter_var(), and new lines are removed from the name.

<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $name = trim($_POST["name"] ?? "");
    $email = filter_var($_POST["email"] ?? "", FILTER_VALIDATE_EMAIL);
    $message = trim($_POST["message"] ?? "");

    // Validate the data
    if ($name === "" || !$email || $message === "") {
        echo "Please fill all fields with a valid email.";
        exit;
    }

    $to = "admin@yourdomain.com";
    $subject = "New message from " . str_replace(["\r", "\n"], " ", $name);
    $body = "Name: $name\nEmail: $email\n\n$message";
    $headers = ["From" => "website@yourdomain.com", "Reply-To" => $email];

    if (mail($to, $subject, $body, $headers)) {
        echo "Thank you, your message is sent.";
    } else {
        echo "Sorry, the message could not be sent.";
    }
}
?>

Why the email may not arrive

  • Local computer: XAMPP and similar tools have no mail server by default, so mail() fails. Use an SMTP service or a tool like Mailpit for testing.
  • Spam folder: emails without a proper From address, SPF and DKIM records often go to spam.
  • Hosting limits: some hosts limit or block mail().

A better way: PHPMailer with SMTP

For real websites most developers use the PHPMailer library with an SMTP server. It supports login, encryption, HTML emails and attachments, and gives clear error messages. Install it with Composer using composer require phpmailer/phpmailer.

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require __DIR__ . "/vendor/autoload.php";

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host = "smtp.example.com";
    $mail->SMTPAuth = true;
    $mail->Username = "user@example.com";
    $mail->Password = "your-smtp-password";
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;

    $mail->setFrom("hello@yourdomain.com", "Tutorials Class");
    $mail->addAddress("student@example.com");
    $mail->Subject = "Welcome to Tutorials Class";
    $mail->Body = "Hello, thanks for joining us.";

    $mail->send();
    echo "Message sent";
} catch (Exception $e) {
    echo "Mailer error: " . $mail->ErrorInfo;
}
?>
Note: Keep the SMTP password in a config file outside the public folder, never inside a page that visitors can open. See PHP Security Tips.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Create a PHP Form with 2 fields Name and Hobbies
Interview Questions & Answers
What are the form method Attribute available for submitting?
How can we submit a form without a submit button?
What is the difference between GET and POST method in PHP?
How to redirect a page in PHP?
How to get the browser details of a visitor in PHP?
How to get the previous page (referrer) URL in PHP?
How to get the IP address of a visitor in PHP?