Current Location: Home> Latest Articles> How to Block or Filter Emails with PHP: Implementing an Email Blacklist

How to Block or Filter Emails with PHP: Implementing an Email Blacklist

M66 2025-07-10

PHP Email Blacklist: Block or Filter Emails from Specific Addresses

In today's internet age, email has become an essential communication tool. However, the increasing volume of spam and malicious emails can be quite bothersome. To address this, PHP provides a solution for blocking or filtering emails from specific addresses using an email blacklist system. This article explains how to implement such a system using PHP.

Creating the Email Blacklist Database

First, you need a database to store the email addresses on the blacklist. MySQL is a commonly used database for this purpose. You can create a simple table with the following SQL statement:

CREATE TABLE email_blacklist ( id INT AUTO_INCREMENT PRIMARY KEY, email VARCHAR(255) NOT NULL );

Connecting to the Database with PHP

Next, use PHP to connect to the MySQL database. Here’s an example of how to do this:

<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>

Checking if an Email is on the Blacklist

To check whether an email address is on the blacklist, we can write a PHP function that queries the database:

<?php
function checkEmailBlacklist($email) {
    global $conn;

    $sql = "SELECT * FROM email_blacklist WHERE email = '$email'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        return true; // Email is on the blacklist
    } else {
        return false; // Email is not on the blacklist
    }
}
?>

Checking the Email Before Sending

Before sending an email, we need to check if the recipient's email address is on the blacklist. If it’s not on the blacklist, we proceed with sending the email; otherwise, we block the email from being sent:

<?php
$to = "recipient@example.com";
$subject = "Example Email";
$body = "This is an example email.";

// Check if the email is on the blacklist
if (!checkEmailBlacklist($to)) {
    $headers = "From: sender@example.com";
    $headers .= "Reply-To: sender@example.com";

    if (mail($to, $subject, $body, $headers)) {
        echo "Email sent successfully.";
    } else {
        echo "Failed to send email.";
    }
} else {
    echo "Email blocked.";
}
?>

Advanced Email Filtering

The above code is a basic example. In real-world applications, you may need to implement additional filtering or more complex business logic, such as inspecting the email subject and body.

Conclusion

Using PHP to implement an email blacklist system can effectively block or filter emails from specific addresses, reducing the risk of spam and malicious emails. We hope this guide helps you build your own email blacklist solution.