EmailEngine.NET
1.0.0
dotnet add package EmailEngine.NET --version 1.0.0
NuGet\Install-Package EmailEngine.NET -Version 1.0.0
<PackageReference Include="EmailEngine.NET" Version="1.0.0" />
<PackageVersion Include="EmailEngine.NET" Version="1.0.0" />
<PackageReference Include="EmailEngine.NET" />
paket add EmailEngine.NET --version 1.0.0
#r "nuget: EmailEngine.NET, 1.0.0"
#:package EmailEngine.NET@1.0.0
#addin nuget:?package=EmailEngine.NET&version=1.0.0
#tool nuget:?package=EmailEngine.NET&version=1.0.0
BCD Email Engine
A comprehensive, modular email sending engine for .NET 8 with monitoring, templating, and advanced features.
๐ 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
- Use Bulk Operations: For multiple emails, use
SendBulkAsyncinstead of multipleSendAsynccalls - Configure Connection Pooling: Adjust
MaxConnectionsbased on your SMTP server limits - Optimize Batch Size: Balance between memory usage and throughput
- Enable Monitoring: Use monitoring to identify bottlenecks
- Use Async/Await: Always use async methods to avoid blocking threads
๐ค Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - 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
- Documentation: Wiki
- Issues: GitHub Issues
- Discussions: GitHub Discussions
๐ท๏ธ 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 | Versions 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. |
-
net8.0
- FluentValidation (>= 11.9.0)
- Microsoft.Extensions.Configuration.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Configuration.Binder (>= 8.0.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Hosting.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Options (>= 8.0.0)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 8.0.0)
- Quartz (>= 3.8.0)
- Serilog (>= 3.1.1)
- Serilog.Extensions.Hosting (>= 8.0.0)
- Serilog.Extensions.Logging (>= 8.0.0)
- System.Reactive (>= 6.0.0)
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 |