PHP mail: Multiple recipients?
The snippet you are looking at demonstrates a fundamental misunderstanding of how the mail() function interacts with your data structure. Currently, your script iterates through the database records but assigns only the last fetched $row['address'] to the $to variable before executing the send command. This means that for every row in your email table, the script ignores all previous addresses and sends a single email to just the final entry found in the query result.
To send one message to multiple recipients simultaneously, you must construct a comma-separated list of email addresses as the value for the $to variable before calling mail(). The underlying mail transfer agent (MTA) interprets a space or a comma followed by a space as a delimiter between distinct recipients.
Here is how you can refactor your logic to handle multiple rows:
include("db.php");
$result = mysql_query("SELECT * FROM email");
$to_list = [];
while($row = mysql_fetch_array($result)) {
$to_list[] = $row['address'];
}
// Join the array with commas and spaces to create a single header value
$all_recipients = implode(', ', $to_list);
if (!empty($all_recipients)) {
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "example@example.com";
// Using standard headers. Note that 'Bcc' allows for hidden recipients if needed.
$headers = "From: " . $from . "\r\n";
mail($all_recipients, $subject, $message, $headers);
}
This approach consolidates all addresses into a single string. When the script executes mail(), it sends one transaction containing the message to every address in that list. From the perspective of the receiving servers, this looks like a standard multi-recipient email, similar to a "Bcc" group send.
However, there is a significant distinction you must be aware of regarding privacy and deliverability. If the recipients are listed in the To header (as shown above), every recipient will see the list of all other email addresses in their headers. This is problematic if your table contains internal staff emails mixed with external client addresses; a client would inadvertently receive the HR department's email address.
If you require that each recipient receives the email individually without seeing the others, you must switch to Blind Carbon Copy (Bcc). In this scenario, you still need to send multiple transactions from your server to the mail queue, but you only list one primary recipient in the To header and move the remaining addresses to the Bcc header.
// Example for privacy-preserving multi-recipient sending
foreach($to_list as $recipient) {
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: " . $from . "\r\n"; // Optional but recommended
// Send to current recipient in To, others in Bcc
mail($recipient, $subject, $message, $headers, null);
}
While the loop method above ensures privacy, it increases the load on your PHP process because mail() is called multiple times. This can lead to rate-limiting issues with your hosting provider or email service provider (ESP) if you are sending a large volume of emails rapidly. Most shared hosting environments and cloud providers have strict limits on the number of emails sent per minute to prevent spam abuse.
Furthermore, relying on the standard mail() function for anything beyond simple testing is generally discouraged in production applications. It lacks robust error reporting; if the recipient's domain is invalid or the message triggers a spam filter, you will not receive immediate feedback unless you implement additional checks using SMTP libraries or services like SendGrid or Mailgun.
For modern PHP projects, particularly those built on top of frameworks like Laravel, handling email delivery usually involves switching from mail() to an SMTP connection or utilizing the framework's native mail queue system. These methods provide better control over headers, allow for asynchronous sending to avoid blocking web requests, and integrate seamlessly with transactional email services that offer deliverability guarantees.
If you are maintaining a legacy codebase where upgrading the entire stack is not immediately feasible, sticking to the mail() function with careful attention to header construction and rate limiting is necessary, but you should plan for a migration to a dedicated SMTP solution eventually.