Prevent Sending Emails to Unsubscribed Users in PHP
When managing email lists, it's essential to respect users' requests to unsubscribe. Such requests can be stored in one or more database tables. The following code demonstrates how to prevent sending emails to unsubscribed users by checking their email against these tables.
The Code to Check Blocked Emails
The following PHP function checks if an email is listed in one or more "unsubscribe" tables. If found, it prevents the email from being sent:
function isEmailBlocked($pdo, $email, $tables) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return true; // Invalid email is treated as blocked
}
foreach ($tables as $table) {
try {
$sql = "SELECT `id` FROM `$table` WHERE `email` = :email LIMIT 1";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->execute();
if ($stmt->rowCount() > 0) {
return true; // Email is found in the table
}
} catch (Exception $e) {
// Optionally handle the exception
// error_log("Exception: " . $e->getMessage());
}
}
return false; // Email is not in any blocked list
}
- Input Validation: The function ensures the email is valid before querying the database.
- Efficiency: Queries are limited to one result (LIMIT 1) to avoid unnecessary overhead.
- Multiple Tables: The function supports checking multiple "unsubscribe" tables.
- Error Handling: You can add logging or other mechanisms to handle exceptions gracefully.
How to Use the Function
Set Up the Blocked Email Tables
Define an array with the names of tables containing blocked email addresses:
$blockedTables = ['dont_send_emails', 'remove_emails'];
Check Before Sending Emails
Call the function before sending an email:
if (isEmailBlocked($dbh, $userEmail, $blockedTables)) {
// Email is blocked; do not send
return false;
}
Summary
By implementing this simple function, you ensure that your email system respects user preferences and avoids sending emails to unsubscribed addresses.
Recommended for you:
Using jQuery and AJAX to dynamically update a page
Image compression with PHP and Bash - quick and dirty
How to transform an array into a Laravel paginated list?
Disclaimer
As far as I know, the script within this page is functional and harmless. However I make no guarantees. I also take no responsibility for any damage you may do when using the script (the chances of any problems occuring are slim but who knows). Please use this script responsibly and judgmentally.