What are the best practices for handling email addresses stored in a text file in PHP for sending individual emails to multiple recipients?
When handling email addresses stored in a text file in PHP for sending individual emails to multiple recipients, it is important to properly sanitize and validate each email address before sending the email. One approach is to read the email addresses from the text file, validate each address using PHP's filter_var function with the FILTER_VALIDATE_EMAIL filter, and then send individual emails to each valid recipient.
<?php
// Read email addresses from a text file
$emails = file('email_addresses.txt', FILE_IGNORE_NEW_LINES);
// Loop through each email address and send individual emails
foreach ($emails as $email) {
$email = trim($email); // Remove any leading or trailing whitespace
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Send email to $email
// Example: mail($email, 'Subject', 'Message');
echo "Email sent to $email\n";
} else {
echo "Invalid email address: $email\n";
}
}
?>