How can PHP Mailer be used to exclude specific email addresses or domains from sending messages?

To exclude specific email addresses or domains from sending messages using PHP Mailer, you can add a condition to check the sender's email address before sending the email. If the sender's email address matches the excluded email addresses or domains, the email will not be sent.

use PHPMailer\PHPMailer\PHPMailer;

// Initialize PHPMailer
$mail = new PHPMailer();

// Set sender's email address
$sender_email = 'sender@example.com';

// Array of excluded email addresses or domains
$excluded_emails = ['blocked@example.com', 'domain.com'];

// Check if sender's email address is in the excluded list
if (!in_array($sender_email, $excluded_emails) && !in_array(substr(strrchr($sender_email, "@"), 1), $excluded_emails)) {
    // Sender is not excluded, proceed with sending the email
    $mail->setFrom($sender_email, 'Sender Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');
    $mail->Subject = 'Subject';
    $mail->Body = 'Message body';
    
    if ($mail->send()) {
        echo 'Email sent successfully';
    } else {
        echo 'Email could not be sent';
    }
} else {
    // Sender is excluded, do not send the email
    echo 'Sender is excluded from sending emails';
}