MailFusion 1.1.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package MailFusion --version 1.1.0                
NuGet\Install-Package MailFusion -Version 1.1.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="MailFusion" Version="1.1.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add MailFusion --version 1.1.0                
#r "nuget: MailFusion, 1.1.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.
// Install MailFusion as a Cake Addin
#addin nuget:?package=MailFusion&version=1.1.0

// Install MailFusion as a Cake Tool
#tool nuget:?package=MailFusion&version=1.1.0                

MailFusion

NuGet License: MIT

<img src="https://raw.githubusercontent.com/ahmedkamalio/DotNet.MailFusion/main/icon.png" alt="MailFusion Icon" width="100" height="100">

A modern, flexible email delivery library for .NET that simplifies sending emails through various providers like SendGrid and Amazon SES. MailFusion offers robust template support, comprehensive error handling, and a clean, strongly-typed API.

Features

  • ๐Ÿ“ง Multiple Email Provider Support
    • SendGrid
    • Amazon SES
    • Development (console output for testing)
    • Custom Email provider support
  • ๐Ÿ“ Template Support
    • Scriban template engine integration
    • HTML and plain text support
    • Template caching for performance
    • Strong typing for template models
    • Custom template engine support
    • Custom template loader support
  • โšก Modern .NET Features
    • Async/await throughout
    • Nullable reference types
    • Record types for immutable data
    • Modern C# features
    • Builder pattern configuration
  • ๐Ÿ›ก๏ธ Robust Error Handling
    • Detailed error information
    • Provider-specific error mapping
    • Strongly-typed error codes
    • Comprehensive logging
  • ๐Ÿงช Development-Friendly
    • Development provider for testing
    • Detailed debugging information
    • Comprehensive XML documentation
    • Rich logging support
    • Sensible defaults

Installation

Install MailFusion via NuGet:

dotnet add package MailFusion

Quick Start

1. Basic Configuration

The simplest way to get started is with the basic configuration in your appsettings.json:

{
  "Email": {
    "Provider": "SendGrid",
    "SendGrid": {
      "ApiKey": "your-api-key"
    }
  }
}

And in your Program.cs or Startup.cs:

services.AddMailFusion(Configuration, Environment);

2. Advanced Configuration

MailFusion supports extensive customization through the builder pattern:

services.AddMailFusion(Configuration, Environment, builder =>
{
    builder
        .UseCustomEmailProvider<MyEmailProvider>()
        .UseCustomTemplateEngine<MyTemplateEngine>()
        .UseCustomTemplateLoader<MyTemplateLoader>();
});

3. Create an Email Template Model

public class WelcomeEmailModel : IEmailTemplateModel
{
    public string Subject => "Welcome to Our Service!";
    public string Email { get; init; }
    public string UserName { get; init; }
}

4. Send an Email

public class EmailService
{
    private readonly IEmailService _emailService;

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

    public async Task SendWelcomeEmailAsync(string userEmail, string userName)
    {
        var model = new WelcomeEmailModel
        {
            Email = userEmail,
            UserName = userName
        };

        var sender = new EmailSender
        {
            Name = "My Service",
            Email = "noreply@myservice.com",
            ReplyEmail = "support@myservice.com"
        };

        var recipients = new[]
        {
            new EmailRecipient { Email = userEmail, Name = userName }
        };

        var result = await _emailService.SendFromTemplateAsync(
            "welcome-email",
            model,
            sender,
            recipients);

        if (result.IsFailure)
        {
            // Handle error
        }
    }
}

Configuration Options

Email Provider Configuration

SendGrid
{
  "Email": {
    "Provider": "SendGrid",
    "SendGrid": {
      "ApiKey": "your-api-key"
    }
  }
}
Amazon SES
{
  "Email": {
    "Provider": "AmazonSes",
    "AmazonSes": {
      "AccessKey": "your-access-key",
      "SecretKey": "your-secret-key",
      "Region": "us-east-1"
    }
  }
}
Development Provider
{
  "Email": {
    "Provider": "Development",
    "Development": {
      "UseColors": true,
      "ShowHtmlBody": true,
      "ShowPlainTextBody": false
    }
  }
}

Template Configuration

Template configuration is optional. If not specified, MailFusion will use these defaults:

  • File-based template provider
  • Templates directory at {BaseDirectory}/Templates/Email

To customize template settings:

{
  "EmailTemplates": {
    "Provider": "File",
    "File": {
      "TemplatesPath": "path/to/templates"
    }
  }
}

Custom Implementations

Custom Email Provider

public class MyEmailProvider : IEmailProvider
{
    public async Task<IResult<Unit>> SendEmailAsync(EmailMessage message, CancellationToken cancellationToken = default)
    {
        // Custom implementation
    }
}

// Registration
services.AddMailFusion(Configuration, Environment, builder =>
{
    builder.UseCustomEmailProvider<MyEmailProvider>();
});

Custom Template Engine

public class MyTemplateEngine : IEmailTemplateEngine
{
    public async Task<IResult<IEmailTemplate>> LoadTemplateAsync<TModel>(
        string templateName, TModel model) where TModel : IEmailTemplateModel
    {
        // Custom implementation
    }
}

// Registration
services.AddMailFusion(Configuration, Environment, builder =>
{
    builder.UseCustomTemplateEngine<MyTemplateEngine>();
});

Custom Template Loader

public class MyTemplateLoader : IEmailTemplateLoader
{
    public async Task<IResult<(string html, string text)>> LoadTemplateAsync(string templateName)
    {
        // Custom implementation
    }
}

// Registration
services.AddMailFusion(Configuration, Environment, builder =>
{
    builder.UseCustomTemplateLoader<MyTemplateLoader>();
});

Template System

When using the default file-based template system, organize your templates as follows:

Templates/
  โ””โ”€โ”€ Email/
      โ”œโ”€โ”€ welcome/
      โ”‚   โ”œโ”€โ”€ welcome.html
      โ”‚   โ””โ”€โ”€ welcome.txt
      โ””โ”€โ”€ order-confirmation/
          โ”œโ”€โ”€ order-confirmation.html
          โ””โ”€โ”€ order-confirmation.txt

Example Template

HTML template (welcome.html):

<h1>Welcome {{ UserName }}!</h1>
<p>Thank you for joining our service.</p>

Text template (welcome.txt):

Welcome {{ UserName }}!

Thank you for joining our service.

Error Handling

MailFusion uses the Result pattern for error handling:

var result = await _emailService.SendFromTemplateAsync(...);

if (result.IsFailure)
{
    var error = result.Error;
    logger.LogError("Failed to send email: {ErrorCode} - {ErrorMessage}",
        error.Code,
        error.Message);
}

Development and Testing

For development and testing, use the Development provider:

{
  "Email": {
    "Provider": "Development"
  }
}

This will output emails to the console instead of sending them.

Logging

MailFusion integrates with Microsoft.Extensions.Logging:

services.AddLogging(builder =>
{
    builder.AddConsole();
    // Add other logging providers as needed
});

Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b my-new-feature
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request

License

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

Acknowledgments

Support

For support, please open an issue in the GitHub repository.


Made with โค๏ธ by Ahmed Kamal

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 is compatible. 
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.1.2 70 11/16/2024
1.1.1 68 11/16/2024
1.1.0 66 11/16/2024
1.0.0 67 11/16/2024