How can PHP be used to handle email bounces in a newsletter mailing list?

When sending out newsletters to a mailing list, it is important to handle email bounces properly. One way to do this is by setting up a bounce email address that receives bounce notifications from the mail server. Then, you can use PHP to parse these bounce emails and update your mailing list accordingly by removing invalid email addresses.

// Code snippet to handle email bounces in a newsletter mailing list

// Set up a bounce email address to receive bounce notifications
$bounce_email = 'bounces@example.com';

// Parse bounce emails and update mailing list
$bounce_message = file_get_contents('php://stdin');

if (strpos($bounce_message, 'Action: failed') !== false) {
    preg_match('/Final-Recipient: rfc822; ([^\s]+)/', $bounce_message, $matches);
    $invalid_email = $matches[1];

    // Update mailing list by removing invalid email address
    $mailing_list = file('mailing_list.txt', FILE_IGNORE_NEW_LINES);
    $updated_mailing_list = array_diff($mailing_list, array($invalid_email));
    file_put_contents('mailing_list.txt', implode("\n", $updated_mailing_list));
}