HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Email (mail)

PHP allows you to send emails directly from a script using the built-in mail() function. This is commonly used for contact forms, registration confirmations, and automated notifications.


The mail() Function Syntax

The mail() function requires three mandatory parameters and allows for optional headers.

mail(to, subject, message, headers, parameters);

1. Sending a Simple Text Email

This is the most basic way to send an email. It uses plain text for the body.

<?php
    $to = "someone@example.com";
    $subject = "My subject";
    $txt = "Hello world!";
    $headers = "From: webmaster@example.com";

    if (mail($to, $subject, $txt, $headers)) {
        echo "Email sent successfully!";
    } else {
        echo "Email delivery failed.";
    }
?>

2. Sending an HTML Email

To send an HTML email, you must specify the **MIME-Version** and **Content-type** in the headers. This tells the recipient's email client to render the message as HTML instead of plain text.

<?php
    $to = "user@example.com";
    $subject = "HTML Email Tutorial";

    $message = "
    <html>
    <head>
    <title>HTML email</title>
    </head>
    <body>
    <p>This email contains HTML Tags!</p>
    <table>
    <tr><th>Firstname</th><th>Lastname</th></tr>
    <tr><td>John</td><td>Doe</td></tr>
    </table>
    </body>
    </html>
    ";

    // Always set content-type when sending HTML email
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

    // More headers
    $headers .= 'From: ' . "\r\n";
    $headers .= 'Cc: myboss@example.com' . "\r\n";

    mail($to, $subject, $message, $headers);
?>
Note: Each header line must be separated by a **CRLF** (\r\n).

Local Development Warning

The mail() function requires a configured mail server (SMTP) to work. On your local machine (using XAMPP or Laragon), it often won't send actual emails unless you configure an external SMTP service (like Gmail) or use a tool like **MailHog** or **Papercut** to "catch" the emails locally.

Security Hint: Never put unvalidated user data (like $_POST['email']) directly into headers. This can lead to **Email Header Injection**, allowing attackers to use your server to send spam.

Summary

  • mail() is the built-in function to send emails.
  • Mandatory fields: To, Subject, and Message.
  • Headers are used for From, Cc, Bcc, and HTML formatting.
  • HTML emails require the Content-type: text/html header.
Professional Alternative: For production apps, many developers prefer libraries like **PHPMailer** or **SwiftMailer** because they offer more features (like attachments) and better reliability than the basic mail() function.

What's Next?

We're nearing the end of our advanced topics! Next, we'll learn how to organize and reuse your code efficiently using **PHP include & require**.