EmailEngine.NET 1.0.0

dotnet add package EmailEngine.NET --version 1.0.0
                    
NuGet\Install-Package EmailEngine.NET -Version 1.0.0
                    
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="EmailEngine.NET" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="EmailEngine.NET" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="EmailEngine.NET" />
                    
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 EmailEngine.NET --version 1.0.0
                    
#r "nuget: EmailEngine.NET, 1.0.0"
                    
#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 EmailEngine.NET@1.0.0
                    
#: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=EmailEngine.NET&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=EmailEngine.NET&version=1.0.0
                    
Install as a Cake Tool

BCD Email Engine

A comprehensive, modular email sending engine for .NET 8 with monitoring, templating, and advanced features.

.NET License NuGet

๐Ÿš€ Features

โœ… Core Features (Implemented)

  • SMTP Provider: Full SMTP email sending with SSL/TLS support
  • Bulk Email Processing: Efficient batch processing with configurable concurrency and retry logic
  • Email Scheduling: Schedule emails for future delivery with simple delay-based implementation
  • Real-time Progress Tracking: Monitor email operations with detailed progress reporting
  • Rich Email Support: HTML/Plain text, file attachments, inline images, custom headers
  • Dependency Injection: Complete integration with Microsoft.Extensions.DependencyInjection
  • Configuration-driven: JSON-based configuration with environment support
  • Comprehensive Error Handling: Robust exception handling with detailed error reporting
  • XML Documentation: Complete API documentation for IntelliSense support

๐Ÿšง Advanced Features (Planned)

  • Multiple Providers: SendGrid, Azure Communication Services, Exchange support
  • Template Engine: Razor and Liquid template processing
  • Advanced Scheduling: Quartz.NET integration for complex scheduling scenarios
  • Queue-based Processing: Background email processing with persistence
  • Advanced Monitoring: Real-time dashboards and metrics collection
  • Multi-tenant Support: Isolated email configurations per tenant

Quick Start

๐Ÿ“ฆ Installation

Package Manager Console

Install-Package BCD.EmailEngine

.NET CLI

dotnet add package BCD.EmailEngine

PackageReference

<PackageReference Include="BCD.EmailEngine" Version="1.0.0" />

โšก Quick Start

1. Configuration

Add EmailEngine configuration to your appsettings.json:

{
  "EmailEngine": {
    "Providers": {
      "Smtp": {
        "Type": "Smtp",
        "Enabled": true,
        "Priority": 1,
        "Settings": {
          "Host": "smtp.gmail.com",
          "Port": "587",
          "EnableSsl": "true",
          "Username": "your-email@gmail.com",
          "Password": "your-app-password",
          "DisplayName": "Your Application",
          "TimeoutSeconds": "30"
        }
      }
    },
    "Monitoring": {
      "EnableRealTimeMonitoring": true,
      "EnablePerformanceCounters": true
    },
    "Logging": {
      "MinimumLevel": "Information",
      "EnableStructuredLogging": true
    }
  }
}

2. Service Registration

Register EmailEngine services in your Program.cs or Startup.cs:

using BCD.EmailEngine.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Add EmailEngine services
builder.Services.AddEmailEngine(builder.Configuration);

// Add logging
builder.Services.AddLogging();

var app = builder.Build();

3. Basic Usage

using BCD.EmailEngine.Core.Interfaces;
using BCD.EmailEngine.Core.Models;

public class EmailController : ControllerBase
{
    private readonly IEmailService _emailService;

    public EmailController(IEmailService emailService)
    {
        _emailService = emailService;
    }

    [HttpPost("send")]
    public async Task<IActionResult> SendEmail()
    {
        // Create email message
        var message = new EmailMessage("Welcome!", "Thank you for joining our service!");
        message.From = new EmailAddress("noreply@yourapp.com", "Your Application");
        message.AddRecipient("user@example.com", "John Doe");

        // Send email
        var result = await _emailService.SendAsync(message);

        if (result.IsSuccess)
        {
            return Ok($"Email sent successfully in {result.Duration.TotalMilliseconds}ms");
        }
        else
        {
            return BadRequest($"Failed to send email: {result.Message}");
        }
    }
}

๐Ÿ“š Usage Examples

HTML Email with Attachments

var message = new EmailMessage("Invoice #12345", "")
{
    BodyType = EmailBodyType.Html,
    Body = @"
        <html>
        <body>
            <h1>Invoice #12345</h1>
            <p>Dear Customer,</p>
            <p>Please find your invoice attached.</p>
            <img src=""cid:logo"" alt=""Company Logo"" />
        </body>
        </html>"
};

message.From = new EmailAddress("billing@company.com", "Company Billing");
message.AddRecipient("customer@example.com");
message.AddCcRecipient("manager@company.com");

// Add file attachment
var pdfAttachment = EmailAttachment.FromFile(@"C:\invoices\12345.pdf", "application/pdf");
message.AddAttachment(pdfAttachment);

// Add inline image
var logoAttachment = EmailAttachment.FromFile(@"C:\assets\logo.png", "image/png", true, "logo");
message.AddAttachment(logoAttachment);

// Add custom headers
message.AddHeader("X-Invoice-Number", "12345");
message.Priority = EmailPriority.High;

var result = await _emailService.SendAsync(message);

Bulk Email Processing

var messages = new List<EmailMessage>();

// Create multiple messages
for (int i = 1; i <= 1000; i++)
{
    var message = new EmailMessage($"Newsletter #{i}", $"This is newsletter content for user {i}");
    message.From = new EmailAddress("newsletter@company.com", "Company Newsletter");
    message.AddRecipient($"user{i}@example.com");
    messages.Add(message);
}

// Configure bulk options
var bulkOptions = new BulkEmailOptions
{
    BatchSize = 50,
    MaxConcurrentOperations = 5,
    DelayBetweenBatches = TimeSpan.FromSeconds(2),
    ContinueOnError = true
};

// Progress tracking
var progress = new Progress<BulkOperationProgress>(p =>
{
    Console.WriteLine($"Progress: {p.ProcessedEmails}/{p.TotalEmails} " +
                     $"(Success: {p.SuccessfulEmails}, Failed: {p.FailedEmails})");
});

// Send bulk emails
var result = await _emailService.SendBulkAsync(messages, bulkOptions, progress);

Console.WriteLine($"Bulk operation completed: {result.Summary}");
Console.WriteLine($"Total duration: {result.TotalDuration.TotalSeconds:F1} seconds");
Console.WriteLine($"Average processing time: {result.AverageProcessingTime:F1} ms");

Scheduled Email

var message = new EmailMessage("Reminder", "Don't forget about your appointment tomorrow!");
message.From = new EmailAddress("reminders@clinic.com", "Clinic Reminders");
message.AddRecipient("patient@example.com");

// Schedule for tomorrow at 9 AM
var sendTime = DateTime.UtcNow.AddDays(1).Date.AddHours(9);

var result = await _emailService.ScheduleAsync(message, sendTime);

Progress Tracking

var progress = new Progress<OperationProgress>(p =>
{
    Console.WriteLine($"Stage: {p.CurrentStage}");
    Console.WriteLine($"Progress: {p.PercentageComplete}%");
    Console.WriteLine($"Message: {p.Message}");
    Console.WriteLine($"Elapsed: {p.ElapsedTime}");
});

var result = await _emailService.SendAsync(message, progress);

๐Ÿ”ง Configuration

Provider Configuration

{
  "EmailEngine": {
    "Providers": {
      "Smtp": {
        "Type": "Smtp",
        "Enabled": true,
        "Priority": 1,
        "Settings": {
          "Host": "smtp.gmail.com",
          "Port": "587",
          "EnableSsl": "true",
          "Username": "your-email@gmail.com",
          "Password": "your-app-password",
          "DisplayName": "Your App Name",
          "TimeoutSeconds": "30"
        },
        "ConnectionPool": {
          "MaxConnections": 10,
          "ConnectionTimeout": "00:00:30",
          "IdleTimeout": "00:05:00"
        },
        "Retry": {
          "MaxAttempts": 3,
          "InitialDelay": "00:00:01",
          "MaxDelay": "00:01:00",
          "BackoffMultiplier": 2.0
        }
      }
    }
  }
}

Security Configuration

{
  "EmailEngine": {
    "Security": {
      "EnableInputValidation": true,
      "EnableHtmlSanitization": true,
      "EnableAttachmentScanning": false,
      "RateLimit": {
        "MaxEmailsPerMinute": 1000,
        "MaxEmailsPerHour": 10000,
        "MaxEmailsPerDay": 100000
      }
    }
  }
}

Monitoring Configuration

{
  "EmailEngine": {
    "Monitoring": {
      "EnableRealTimeMonitoring": true,
      "EnablePerformanceCounters": true,
      "EnableResourceMonitoring": true,
      "MonitoringBufferSize": 1000,
      "MonitoringFlushInterval": "00:00:30"
    }
  }
}

๐Ÿ—๏ธ Architecture

Core Components

  • IEmailService: Main service interface for sending emails
  • IEmailProvider: Provider interface for different email services (SMTP, SendGrid, etc.)
  • EmailMessage: Rich email message model with attachments and metadata
  • IEmailEngineMonitor: Monitoring and telemetry interface

Provider Architecture

The library uses a provider-based architecture that allows for easy extension:

public interface IEmailProvider
{
    string ProviderName { get; }
    Task<EmailOperationResult> SendAsync(EmailMessage message, CancellationToken cancellationToken = default);
    Task<BulkEmailOperationResult> SendBulkAsync(IEnumerable<EmailMessage> messages, BulkEmailOptions? options = null, IProgress<BulkOperationProgress>? progress = null, CancellationToken cancellationToken = default);
    Task<bool> TestConnectionAsync(CancellationToken cancellationToken = default);
    Task<ProviderHealthStatus> GetHealthStatusAsync(CancellationToken cancellationToken = default);
}

๐Ÿงช Testing

Run the test suite:

dotnet test

Run tests with coverage:

dotnet test --collect:"XPlat Code Coverage"

Unit Testing Example

[Test]
public async Task SendAsync_ValidMessage_ShouldReturnSuccess()
{
    // Arrange
    var mockProvider = new Mock<IEmailProvider>();
    var mockOptions = new Mock<IOptions<EmailEngineOptions>>();
    var mockLogger = new Mock<ILogger<EmailService>>();

    mockOptions.Setup(x => x.Value).Returns(new EmailEngineOptions());
    mockProvider.Setup(x => x.ProviderName).Returns("TestProvider");
    mockProvider.Setup(x => x.GetHealthStatusAsync(It.IsAny<CancellationToken>()))
        .ReturnsAsync(new ProviderHealthStatus { IsHealthy = true });

    var emailService = new EmailService(
        new[] { mockProvider.Object },
        mockOptions.Object,
        mockLogger.Object);

    var message = new EmailMessage("Test", "Test Body");
    message.From = new EmailAddress("from@test.com");
    message.AddRecipient("to@test.com");

    var expectedResult = new EmailOperationResult
    {
        IsSuccess = true,
        Message = "Email sent successfully"
    };

    mockProvider.Setup(x => x.SendAsync(It.IsAny<EmailMessage>(), It.IsAny<CancellationToken>()))
        .ReturnsAsync(expectedResult);

    // Act
    var result = await emailService.SendAsync(message);

    // Assert
    Assert.IsTrue(result.IsSuccess);
    Assert.AreEqual("Email sent successfully", result.Message);
}

๐Ÿ“‹ Error Handling

EmailEngine provides comprehensive error handling:

try
{
    var result = await _emailService.SendAsync(message);
    if (!result.IsSuccess)
    {
        // Handle business logic errors
        foreach (var error in result.Errors)
        {
            _logger.LogError("Email error: {Error}", error);
        }
    }
}
catch (EmailValidationException ex)
{
    // Handle validation errors
    foreach (var error in ex.ValidationErrors)
    {
        _logger.LogError("Validation error: {Error}", error);
    }
}
catch (ProviderException ex)
{
    // Handle provider-specific errors
    _logger.LogError(ex, "Provider {Provider} failed: {Message}", ex.ProviderName, ex.Message);
}
catch (EmailEngineException ex)
{
    // Handle general EmailEngine errors
    _logger.LogError(ex, "EmailEngine error: {Message} (Code: {Code})", ex.Message, ex.ErrorCode);
}

๐Ÿš€ Performance Tips

  1. Use Bulk Operations: For multiple emails, use SendBulkAsync instead of multiple SendAsync calls
  2. Configure Connection Pooling: Adjust MaxConnections based on your SMTP server limits
  3. Optimize Batch Size: Balance between memory usage and throughput
  4. Enable Monitoring: Use monitoring to identify bottlenecks
  5. Use Async/Await: Always use async methods to avoid blocking threads

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ› ๏ธ Roadmap

  • SendGrid provider implementation
  • Azure Communication Services provider
  • Template engine integration (Razor, Liquid)
  • Queue-based email processing
  • Advanced retry policies
  • Email analytics and tracking
  • Multi-tenant support

๐Ÿ“ž Support

๐Ÿท๏ธ Version History

v1.0.0 (2024-01-XX)

  • Initial release
  • SMTP provider support
  • Bulk email processing
  • Progress tracking and monitoring
  • Comprehensive XML documentation
  • .NET 8 support

โœ… Implementation Status

Completed Features

  • โœ… Core Architecture: Modular provider-based architecture
  • โœ… SMTP Provider: Full SMTP implementation with SSL/TLS, authentication, and timeout support
  • โœ… Email Models: Rich email message models with attachments, headers, and metadata
  • โœ… Bulk Processing: High-performance bulk email processing with configurable batching
  • โœ… Progress Tracking: Real-time progress reporting for individual and bulk operations
  • โœ… Scheduling: Simple delay-based email scheduling
  • โœ… Error Handling: Comprehensive exception hierarchy with detailed error reporting
  • โœ… Configuration: JSON-based configuration with environment support
  • โœ… Dependency Injection: Full integration with Microsoft.Extensions.DependencyInjection
  • โœ… XML Documentation: Complete API documentation for all public members
  • โœ… Unit Tests: Comprehensive test suite with 25+ passing tests
  • โœ… Monitoring Interface: IEmailEngineMonitor for telemetry and monitoring
  • โœ… Health Checks: Provider health status monitoring

In Development

  • ๐Ÿšง Additional Providers: SendGrid, Azure Communication Services
  • ๐Ÿšง Template Engine: Razor and Liquid template processing
  • ๐Ÿšง Advanced Scheduling: Quartz.NET integration
  • ๐Ÿšง Enhanced Monitoring: Real-time metrics and dashboards

Planned Features

  • ๐Ÿ“‹ Queue Processing: Background email processing with persistence
  • ๐Ÿ“‹ Email Tracking: Read receipts and analytics
  • ๐Ÿ“‹ Multi-tenant Support: Isolated configurations per tenant
  • ๐Ÿ“‹ Advanced Security: Content filtering and rate limiting

Made with โค๏ธ by the EmailEngine Team

Product Compatible and additional computed target framework versions.
.NET 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 was computed.  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 was computed.  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.0 237 9/21/2025