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 requires three mandatory parameters and allows for optional headers.
mail(to, subject, message, headers, parameters);
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.";
}
?>
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);
?>
\r\n).
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.
$_POST['email']) directly into headers. This can lead to **Email Header Injection**, allowing attackers to use your server to send spam.
mail() function.
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**.