PHP Mail
Sending emails from PHP applications
📧 What is PHP Mail?
PHP's mail() function allows you to send emails directly from your scripts. It's perfect for contact forms, notifications, password resets, and automated messages to users or administrators.
<?php
// Simple email
mail("[email protected]", "Hello", "This is a test email!");
echo "Email sent!";
?>
Output:
Mail Function Components
HTML Emails
Send formatted HTML content
<?php
$headers = "Content-type: text/html";
mail("[email protected]", "Hi",
"<h1>Hello!</h1>", $headers);
?>
Attachments
Include files with emails
<?php
// Requires multipart headers
// and base64 encoding
?>
Headers
Configure email metadata
<?php
$headers = "From: [email protected]";
mail("[email protected]", "Hi",
"Message", $headers);
?>
🔹 Basic Email Sending
The mail() function requires three parameters: recipient email, subject, and message body. It returns true on success and false on failure.
<?php
$to = "[email protected]";
$subject = "Welcome to Our Website";
$message = "Thank you for signing up! We're excited to have you.";
if (mail($to, $subject, $message)) {
echo "Email sent successfully!";
} else {
echo "Failed to send email.";
}
?>
Output:
🔹 Adding Email Headers
Headers provide additional information about the email like sender, reply-to address, and content type. Separate multiple headers with \r\n line breaks.
<?php
$to = "[email protected]";
$subject = "Newsletter Subscription";
$message = "You've been subscribed to our monthly newsletter.";
// Set headers
$headers = "From: [email protected]\r\n";
$headers .= "Reply-To: [email protected]\r\n";
$headers .= "X-Mailer: PHP/" . phpversion();
if (mail($to, $subject, $message, $headers)) {
echo "Newsletter email sent!";
} else {
echo "Email failed.";
}
?>
Output:
🔹 Sending HTML Emails
To send HTML-formatted emails, set the Content-type header to text/html. This allows you to use HTML tags for styling and structure.
<?php
$to = "[email protected]";
$subject = "Order Confirmation";
$message = "
<html>
<head>
<title>Order Confirmation</title>
</head>
<body>
<h2 style='color: #4CAF50;'>Thank You for Your Order!</h2>
<p>Your order <strong>#12345</strong> has been confirmed.</p>
<p>We'll send you a shipping notification soon.</p>
</body>
</html>
";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "From: [email protected]\r\n";
mail($to, $subject, $message, $headers);
echo "HTML email sent!";
?>
Output:
🔹 Multiple Recipients
Send emails to multiple recipients by separating addresses with commas. You can also use CC (carbon copy) and BCC (blind carbon copy) headers.
<?php
$to = "[email protected], [email protected]";
$subject = "Team Meeting Reminder";
$message = "Don't forget our team meeting tomorrow at 10 AM.";
$headers = "From: [email protected]\r\n";
$headers .= "Cc: [email protected]\r\n";
$headers .= "Bcc: [email protected]\r\n";
if (mail($to, $subject, $message, $headers)) {
echo "Email sent to multiple recipients!";
}
?>
Output:
Recipient Types:
- To: Primary recipients (visible to all)
- Cc: Carbon copy (visible to all)
- Bcc: Blind carbon copy (hidden from others)
🔹 Contact Form Example
A practical example of using PHP mail() for a contact form. This validates input and sends a formatted email to the site administrator.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['name']);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$user_message = htmlspecialchars($_POST['message']);
// Validate email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$to = "[email protected]";
$subject = "New Contact Form Submission";
$message = "Name: $name\n";
$message .= "Email: $email\n\n";
$message .= "Message:\n$user_message";
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
if (mail($to, $subject, $message, $headers)) {
echo "Thank you! Your message has been sent.";
} else {
echo "Sorry, there was an error sending your message.";
}
} else {
echo "Invalid email address.";
}
}
?>
Output:
🔹 Email Validation
Always validate email addresses before sending. PHP provides built-in filters to check if an email format is valid and sanitize user input.
<?php
function validateEmail($email) {
// Remove illegal characters
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate email format
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
return true;
}
return false;
}
// Test emails
$test1 = "[email protected]";
$test2 = "invalid.email@";
$test3 = "[email protected]";
echo "$test1: " . (validateEmail($test1) ? "Valid" : "Invalid") . "\n";
echo "$test2: " . (validateEmail($test2) ? "Valid" : "Invalid") . "\n";
echo "$test3: " . (validateEmail($test3) ? "Valid" : "Invalid");
?>
Output:
🔹 Preventing Email Injection
Protect your mail function from header injection attacks. Always validate and sanitize user input, especially in headers and email addresses.
<?php
function sanitizeEmail($email) {
// Remove any header injection attempts
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Check for newlines and carriage returns
if (preg_match("/[\r\n]/", $email)) {
return false;
}
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
function sanitizeString($string) {
// Remove potential injection characters
$string = str_replace(["\r", "\n", "%0a", "%0d"], '', $string);
return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
}
// Safe email sending
$email = sanitizeEmail($_POST['email'] ?? '');
$name = sanitizeString($_POST['name'] ?? '');
if ($email) {
$headers = "From: [email protected]\r\n";
mail("[email protected]", "Contact", "From: $name", $headers);
echo "Secure email sent!";
} else {
echo "Invalid email address.";
}
?>
Security Best Practices:
- Always validate email addresses
- Sanitize all user input
- Never trust data from forms directly
- Check for newline characters in headers
- Use prepared statements for database queries
- Consider using PHPMailer library for production
🔹 Common Mail Issues
Troubleshooting Tips:
- Emails not sending: Check server mail configuration
- Emails in spam: Add proper SPF/DKIM records
- Headers not working: Use \r\n for line breaks
- HTML not rendering: Set Content-type header
- Localhost issues: Configure sendmail or use SMTP
Better Alternatives:
- PHPMailer: Popular library with SMTP support
- SwiftMailer: Feature-rich email library
- Symfony Mailer: Modern email component
- Email Services: SendGrid, Mailgun, Amazon SES