PHP form send email to multiple recipients
Stefan Bogdanescu
Founder & Senior Architect
Sending Emails to Multiple Recipients in PHP: A Practical Guide
As developers, one of the most common tasks we encounter is sending notifications or forms results via email. When you start with a simple script using PHP's native mail() function, it's easy to target a single recipient. However, real-world applications often require sending emails to multiple addresses—a primary recipient, carbon copy (CC), and blind carbon copy (BCC).
If you are running into issues or need more control over these complex scenarios, simply listing addresses in your code might not be the most reliable approach. As a senior developer, I recommend understanding both the simple method and the robust, industry-standard solution.
The Limitation of the Native mail() Function
Your existing code uses the native PHP mail() function:
@mail($email_to, $email_subject, $email_message, $headers);
When using this function directly, managing multiple recipients becomes tricky because the underlying mail server configuration dictates how addresses are handled. While you can try to manipulate the $headers string (using To:, CC:, and BCC:), this method is often unreliable, especially when dealing with external SMTP servers or complex security requirements.
Method 1: Modifying Headers for Multiple Recipients
For basic scenarios where your server is correctly configured to handle multiple recipients via the headers, you can list all desired addresses in the $headers string. This involves setting the To, CC, and BCC fields explicitly.
Here is how you would modify your code to include multiple recipients:
<?php
if(isset($_POST['email'])) {
// Define all recipients
$recipients = [
"recipient1@example.com",
"recipient2@another.net",
"recipient3@third.org"
];
$email_subject = "MVP Nomination";
function died($error) {
// ... (Error handling function remains the same)
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// ... (Input validation remains the same)
$username = $_POST['username'];
$body = $_POST['body'];
$email_from = $_POST['email'];
// ... (Validation logic omitted for brevity)
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "Name: ".clean_string($username)."\n";
$email_message .= "Comments: ".clean_string($body)."\n";
// --- MODIFIED EMAIL HEADER LOGIC ---
$to_addresses = implode(', ', $recipients); // List all 'To' addresses
$headers = 'From: ' . $email_from . "\r\n" .
'Reply-To: ' . $email_from . "\r\n" .
'X-Mailer: PHP/' . phpversion() . "\r\n" .
'To: ' . $to_addresses; // Set the primary recipient(s)
// Note: Handling CC/BCC reliably with native mail() is often problematic.
@mail($email_to, $email_subject, $email_message, $headers);
}
header("Location: ThankYou.html");
?>
While this works for very simple setups, relying on server-side mail() functions can be fragile because it bypasses modern security protocols and robust error checking. For building scalable and reliable applications, especially when dealing with sensitive data or complex delivery requirements, you should move away from the native function.
Method 2: The Professional Approach with SMTP Libraries (Recommended)
The professional standard for sending emails in PHP is to use a dedicated library that interfaces with an external SMTP (Simple Mail Transfer Protocol) server (like SendGrid, Mailgun, or Gmail). This method offers superior deliverability, handles authentication securely, and provides detailed error logging.
Libraries like PHPMailer are essential for this level of application development. When you start building larger systems, integrating services that follow modern standards is crucial. If you are architecting a project, understanding service integration patterns is key, much like how applications are structured in frameworks like Laravel.
Example using an SMTP approach (Conceptual)
Instead of using mail(), you would use a class from a library to establish a connection:
// Conceptual example using a hypothetical Mailer class
require 'vendor/autoload.php'; // Composer autoload
use PHPMailer\PHPMailer\PHPMailer;
$mail = new PHPMailer(true);
try {
// Server settings (SMTP details, username, password)
$mail->isSMTP();
$mail->Host = 'smtp.example.com'; // Your SMTP server
$mail->SMTPAuth = true;
$mail->Username = 'your_smtp_user';
$mail->Password = 'your_smtp_password';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
// Recipients (This is where you add multiple emails easily)
$mail->setFrom('sender@example.com', 'Sender Name');
$mail->addAddress('recipient1@example.com'); // Primary recipient
$mail->addAddress('recipient2@another.net'); // Secondary recipient
// Content
$mail->isHTML(true);
$mail->Subject = 'MVP Nomination';
$mail->Body = '<h1>Form Details</h1><p>...</p>';
$mail->send();
echo 'Message has been sent successfully';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
Conclusion
To summarize, while you can attempt to manage multiple recipients by manipulating headers with the native mail() function, this is brittle and not recommended for production applications. For any serious PHP project, including form submissions or notifications, always opt for a dedicated SMTP library like PHPMailer. This ensures reliable delivery, proper security handling, and the ability to manage complex recipient lists (To, CC, BCC) seamlessly. By adopting these robust tools, you build software that is scalable, secure, and maintainable—principles central to modern application development, much like those championed within the Laravel ecosystem.