Zetian.AntiSpam 1.0.4

Prefix Reserved
dotnet add package Zetian.AntiSpam --version 1.0.4
                    
NuGet\Install-Package Zetian.AntiSpam -Version 1.0.4
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Zetian.AntiSpam" Version="1.0.4" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Zetian.AntiSpam" Version="1.0.4" />
                    
Directory.Packages.props
<PackageReference Include="Zetian.AntiSpam" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Zetian.AntiSpam --version 1.0.4
                    
#r "nuget: Zetian.AntiSpam, 1.0.4"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Zetian.AntiSpam@1.0.4
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Zetian.AntiSpam&version=1.0.4
                    
Install as a Cake Addin
#tool nuget:?package=Zetian.AntiSpam&version=1.0.4
                    
Install as a Cake Tool

Zetian.AntiSpam - Advanced Spam Protection for SMTP

NuGet-Version NuGet-Download License

Comprehensive anti-spam solution for Zetian SMTP Server with multiple detection methods, machine learning, and flexible configuration options.

⚡ Features

  • 📊 Statistics - Detailed metrics and reporting
  • 🚫 RBL/DNSBL - Realtime blackhole list checking
  • 🔧 Extensible - Easy to add custom spam checkers
  • 📧 DKIM/DMARC - Email authentication protocols
  • 🛡️ SPF Validation - Sender Policy Framework verification
  • ⏱️ Greylisting - Temporary rejection for unknown senders
  • High Performance - Parallel checking with timeout support
  • 🤖 Bayesian Filtering - Machine learning-based spam detection

📦 Installation

# Install Zetian SMTP Server (required)
dotnet add package Zetian

# Install AntiSpam Extension
dotnet add package Zetian.AntiSpam

🚀 Quick Start

Basic Anti-Spam Setup

using Zetian.Server;
using Zetian.AntiSpam.Extensions;

// Create SMTP server
var server = new SmtpServerBuilder()
    .Port(25)
    .ServerName("My SMTP Server")
    .Build();

// Add anti-spam with default settings
server.AddAntiSpam();

await server.StartAsync();

Custom Configuration

// Configure anti-spam features
server.AddAntiSpam(builder => builder
    .EnableSpf(failScore: 50)
    .EnableRbl("zen.spamhaus.org", "bl.spamcop.net")
    .EnableBayesian(spamThreshold: 0.85)
    .EnableGreylisting(initialDelay: TimeSpan.FromMinutes(5))
    .WithOptions(options =>
    {
        options.RejectThreshold = 60;
        options.TempFailThreshold = 40;
        options.RunChecksInParallel = true;
    }));

Aggressive Protection

// Use aggressive anti-spam settings
server.AddAntiSpam(builder => builder.UseAggressive());

Lenient Protection

// Use lenient settings for trusted environments
server.AddAntiSpam(builder => builder.UseLenient());

🎯 Individual Features

SPF Checking Only

server.AddSpfCheck(failScore: 50);

RBL/DNSBL Checking

server.AddRblCheck(
    "zen.spamhaus.org",
    "bl.spamcop.net",
    "b.barracudacentral.org"
);

Greylisting

// Add greylisting
server.AddGreylisting(initialDelay: TimeSpan.FromMinutes(5));

// Note: Domain whitelisting needs to be done at greylisting creation
// or by accessing the GreylistingChecker directly
var greylistingChecker = new GreylistingChecker(
    initialDelay: TimeSpan.FromMinutes(5));
greylistingChecker.Whitelist("trusted.com");
server.AddSpamChecker(greylistingChecker);

Bayesian Filtering

// Option 1: Add Bayesian to server
server.AddBayesianFilter(spamThreshold: 0.9);

// Option 2: Work with Bayesian directly for training
var bayesianFilter = new BayesianSpamFilter(spamThreshold: 0.9);
await bayesianFilter.TrainSpamAsync("spam content");
await bayesianFilter.TrainHamAsync("legitimate content");

// Then add trained filter to server
server.AddSpamChecker(bayesianFilter);

DKIM Signature Verification

// Add DKIM checking with strict mode
server.AddDkimCheck(
    failScore: 40,
    strictMode: true  // Require all essential headers to be signed
);

DMARC Policy Enforcement

// Add DMARC checking with policy enforcement
server.AddDmarcCheck(
    failScore: 70,        // Score for reject policy
    quarantineScore: 50,  // Score for quarantine policy
    enforcePolicy: true   // Enforce DMARC policies
);

Complete Email Authentication (SPF + DKIM + DMARC)

// Add all three authentication methods in one call
server.AddEmailAuthentication(
    strictMode: true,      // Strict DKIM validation
    enforcePolicy: true    // Enforce DMARC policies
);

// Or use the builder pattern
server.AddAntiSpam(builder => builder
    .EnableEmailAuthentication(strictMode: true, enforcePolicy: true)
    .WithOptions(options => {
        options.RejectThreshold = 60;
        options.EnableDetailedLogging = true;
    }));

🔧 Advanced Configuration

Custom Spam Checker

using Zetian.AntiSpam.Abstractions;

public class CustomSpamChecker : ISpamChecker
{
    public string Name => "Custom";
    public bool IsEnabled { get; set; } = true;

    public async Task<SpamCheckResult> CheckAsync(
        ISmtpMessage message,
        ISmtpSession session,
        CancellationToken cancellationToken)
    {
        // Custom logic here
        if (IsSpam(message))
        {
            return SpamCheckResult.Spam(75, "Custom rule triggered");
        }
        
        return SpamCheckResult.Clean(0);
    }
}

// Add custom checker
server.AddSpamChecker(new CustomSpamChecker());

Builder Pattern

var builder = new AntiSpamBuilder()
    .WithDnsClient(customDnsClient)
    .EnableSpf()
    .EnableRbl(new[]
    {
        new RblProvider
        {
            Name = "Custom RBL",
            Zone = "custom.rbl.org",
            ExpectedResponses = ["127.0.0.2"]
        }
    })
    .EnableBayesian()
    .AddChecker(new CustomSpamChecker());

var antiSpamService = builder.Build();

📊 Monitoring & Statistics

// Get anti-spam statistics
// NOTE: Currently returns empty stats due to implementation limitations
// Future versions will properly track statistics
var stats = server.GetAntiSpamStatistics();
Console.WriteLine($"Messages Checked: {stats.MessagesChecked}");
Console.WriteLine($"Messages Blocked: {stats.MessagesBlocked}");
Console.WriteLine($"Block Rate: {stats.BlockRate:F1}%");

// Work with Bayesian filter directly
var bayesianFilter = new BayesianSpamFilter();
await bayesianFilter.TrainSpamAsync("spam content here");
await bayesianFilter.TrainHamAsync("legitimate content here");

// Get Bayesian statistics
var bayesianStats = bayesianFilter.GetStatistics();
Console.WriteLine($"Total Spam Messages: {bayesianStats.TotalSpamMessages}");
Console.WriteLine($"Total Ham Messages: {bayesianStats.TotalHamMessages}");
Console.WriteLine($"Unique Words: {bayesianStats.UniqueWords}");

🎓 Training Bayesian Filter

From Files

// Create and train Bayesian filter
var bayesianFilter = new BayesianSpamFilter();

// Load training data
var spamEmails = Directory.GetFiles("spam/", "*.eml")
    .Select(File.ReadAllText);

var hamEmails = Directory.GetFiles("ham/", "*.eml")
    .Select(File.ReadAllText);

// Train the filter
foreach (var spam in spamEmails)
{
    await bayesianFilter.TrainSpamAsync(spam);
}

foreach (var ham in hamEmails)
{
    await bayesianFilter.TrainHamAsync(ham);
}

// Add trained filter to server
server.AddSpamChecker(bayesianFilter);

Interactive Training

// Create Bayesian filter for training
var bayesianFilter = new BayesianSpamFilter();
server.AddSpamChecker(bayesianFilter);

server.MessageReceived += async (sender, e) =>
{
    // Let user classify messages
    if (UserMarksAsSpam(e.Message))
    {
        var content = ExtractContent(e.Message);
        await bayesianFilter.TrainSpamAsync(content);
    }
};

🛠️ Score Interpretation

Score Range Action Description
0-30 Accept Clean message
30-50 Accept with caution Possible spam indicators
50-70 Greylist/Temp Reject Likely spam
70-90 Reject High confidence spam
90-100 Hard Reject Definite spam

🔍 SPF Results

Result Score Impact Meaning
Pass 0 Sender authorized
None 5 No SPF record
Neutral 10 Neither authorized nor forbidden
SoftFail 30 Probably not authorized
Fail 50 Not authorized

🔐 DKIM Results

Result Score Impact Meaning
Pass 0 Valid signature
None 10 No DKIM signature
Fail 40 Invalid signature
Policy 20 Policy violation (e.g., expired)
TempError 0 Temporary failure

📋 DMARC Results

Policy Score Impact Action
None 0 Monitoring only
Quarantine 50 Mark as suspicious
Reject 70 Reject message
No Record 0 No DMARC policy

🌐 Default RBL Providers

  • SpamCop - User-reported spam
  • Barracuda - Commercial spam database
  • Spamhaus ZEN - Comprehensive spam/exploit list
  • SORBS - Multiple spam databases (disabled by default)
  • UCEPROTECT - Aggressive blocking (disabled by default)

⚙️ Configuration Options

public class AntiSpamOptions
{
    // Score threshold for rejection (default: 50)
    public double RejectThreshold { get; set; }
    
    // Score threshold for temp failure (default: 30)
    public double TempFailThreshold { get; set; }
    
    // Run checks in parallel (default: true)
    public bool RunChecksInParallel { get; set; }
    
    // Timeout per checker (default: 10 seconds)
    public TimeSpan CheckerTimeout { get; set; }
    
    // Continue after spam detection (default: false)
    public bool ContinueOnSpamDetection { get; set; }
    
    // Enable detailed logging (default: false)
    public bool EnableDetailedLogging { get; set; }
}

📚 Best Practices

  1. Regular Updates - Keep RBL lists and training data current
  2. Whitelist Partners - Add trusted partners to greylisting whitelist
  3. Train Bayesian - Provide adequate training data for better accuracy
  4. Monitor Statistics - Regularly review block rates and adjust thresholds
  5. Use Multiple Methods - Combine different checkers for better detection
  6. Start Conservative - Begin with lenient settings and adjust based on false positives

🔒 Security Considerations

  • Bayesian filters need balanced training data
  • Greylisting may delay legitimate mail initially
  • RBL queries may expose client IPs to third parties
  • SPF checks require DNS lookups - ensure reliable DNS

🚀 Performance Tips

  • Limit RBL providers to essential ones
  • Set appropriate timeouts for DNS queries
  • Pre-train Bayesian filter before deployment
  • Use caching DNS client for repeated lookups
  • Enable parallel checking for better performance

📋 Requirements

  • Windows, Linux, or macOS
  • .NET 6.0, 7.0, 8.0, 9.0, or 10.0
  • Zetian SMTP Server package
  • DnsClient.NET for DNS lookups

📚 Documentation & Support

📄 License

MIT License - see LICENSE


Built with ❤️ for the .NET community

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.4 125 11/1/2025
1.0.3 220,264 10/29/2025
1.0.2 232 10/29/2025
1.0.1 605,108 10/29/2025
1.0.0 225,950 10/29/2025

All changes are detailed at https://zetian.soferity.com/changelog.