基于PHP+AWS SMTP的邮件脚本意外重复发送问题求助
Hey there, let's figure out why your email script is sending duplicate messages to the first few users—this is a super common loop structure issue, so we can fix it quickly!
Most Likely Cause: Nested Loop Overlap
It sounds like your script has a nested loop that's iterating over all users for every recipient. Here's the breakdown of what's happening:
- You’re first looping through each user to set them as the email recipient
- Then, inside that loop, you’re looping through all users again to generate or send emails
This directly leads to the pattern you’re seeing:
- 1st recipient gets 3 emails (one for every user in the inner loop)
- 2nd recipient gets 2 emails (if the inner loop starts from their index or just runs through remaining users)
- 3rd recipient gets 1 email (only their own entry in the inner loop)
Fix: Simplify to a Single User Loop
The fix is straightforward—you only need one loop that iterates over each user once, sending a single tailored email per user.
Example of the Problematic Code
Here’s what your current script might look like (showing the nested loop mistake):
// Fetch all users from your database $users = $pdo->query("SELECT id, email, name FROM users")->fetchAll(PDO::FETCH_ASSOC); // Outer loop: each user is marked as a recipient foreach ($users as $recipient) { // Inner loop: iterate over ALL users again (this is where things go wrong!) foreach ($users as $userData) { // Send email to $recipient using $userData's details sendAwsSmtpEmail( $recipient['email'], "Update for {$userData['name']}", "Here's your personalized content..." ); } }
Corrected Code
Replace the nested loops with a single loop that sends one email per user, using their unique data:
// Fetch all users from your database $users = $pdo->query("SELECT id, email, name FROM users")->fetchAll(PDO::FETCH_ASSOC); // Single loop: one email per user, targeted to their own inbox foreach ($users as $user) { // Send email TO THIS USER, using THEIR specific data sendAwsSmtpEmail( $user['email'], "Update for {$user['name']}", "Here's your personalized content just for you..." ); }
Additional Checks to Confirm
- Add debug logs: Insert a line like
error_log("Sending email to: {$user['email']}");inside your loop. Check your server logs to see exactly which recipients are getting emails when—this will confirm if the loop is behaving as expected. - Verify database queries: Make sure you’re not re-fetching the entire user list inside the loop (that could accidentally create unintended nested iteration).
- Double-check AWS SMTP setup: While less likely given your specific pattern, confirm your SMTP client isn’t queuing messages incorrectly. But the loop structure is almost certainly the main culprit here.
内容的提问来源于stack exchange,提问作者remedcu

