FluentEmail Documentation

repository·master·Indexed 25 days ago

https://github.com/lukencode/fluentemail

An all-in-one email sending library for .NET and .NET Core featuring a fluent interface. Supports multiple rendering engines including Razor and Liquid, and integrates with various mail providers such as SMTP, SendGrid, Mailgun, Mailtrap, and MailKit.

Tokens
2K
Snippets
9
Records
12
Agent score
35%

What's inside FluentEmail

  1. Configure FluentEmail with Dependency Injection

    master

    In .NET applications, you can configure FluentEmail in ConfigureServices using helper methods. This injects IFluentEmail (for single emails) and IFluentEmailFactory (for multiple emails in a single context) into your service container.

    Common configuration methods include .AddRazorRenderer(), .AddSmtpSender(), and other provider-specific registration methods.

    public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddFluentEmail("fromemail@test.test")
            .AddRazorRenderer()
            .AddSmtpSender("localhost", 25);
    }
  2. Install FluentEmail NuGet packages

    master

    FluentEmail is modular. You must install the core library along with the specific sender and renderer packages you intend to use.

    Core Library

    • FluentEmail.Core: The domain model and basic defaults.

    Renderers

    • FluentEmail.Razor: Uses Razor templates (via RazorLight).
    • FluentEmail.Liquid: Uses Liquid templates (via Fluid).

    Mail Provider Integrations

    • FluentEmail.Smtp: Send via SMTP server.
    • FluentEmail.Mailgun: Send via MailGun's REST API.
    • FluentEmail.SendGrid: Send via SendGrid API.
    • FluentEmail.Mailtrap: Send to Mailtrap (uses SMTP).
    • FluentEmail.MailKit: Send using the MailKit library.
  3. Inject IFluentEmail into services

    master

    Once configured in DI, you can request IFluentEmail in your class constructors to send emails.

    public class EmailService {
    
       private IFluentEmail _fluentEmail;
    
       public EmailService(IFluentEmail fluentEmail) {
         _fluentEmail = fluentEmail;
       }
    
       public async Task Send() {
         await _fluentEmail.To("hellO@gmail.com")
         .Body("The body").SendAsync();
       }
    }
  4. Basic usage of FluentEmail

    master

    You can build and send an email using a fluent interface. Use .From(), .To(), .Subject(), and .Body() to define the email content, then call .SendAsync() to dispatch it.

    var email = await Email
        .From("john@email.com")
        .To("bob@email.com", "bob")
        .Subject("hows it going bob")
        .Body("yo bob, long time no see!")
        .SendAsync();
  5. Use Razor templates with FluentEmail

    master

    To use Razor templates, ensure you have the FluentEmail.Razor package. You can set the Email.DefaultRenderer globally or use the renderer configured via DI. Use .UsingTemplate(template, model) to pass a string template and an anonymous object or model.

    // Using Razor templating package (or set using AddRazorRenderer in services)
    Email.DefaultRenderer = new RazorRenderer();
    
    var template = "Dear @Model.Name, You are totally @Model.Compliment.";
    
    var email = Email
        .From("bob@hotmail.com")
        .To("somedude@gmail.com")
        .Subject("woo nuget")
        .UsingTemplate(template, new { Name = "Luke", Compliment = "Awesome" });
  6. Use a template file from disk

    master

    Load a template directly from a file path on the file system using .UsingTemplateFromFile(path, model).

    var email = Email
        .From("bob@hotmail.com")
        .To("somedude@gmail.com")
        .Subject("woo nuget")
        .UsingTemplateFromFile($"{Directory.GetCurrentDirectory()}/Mytemplate.cshtml", new { Name = "Rad Dude" });
  7. Use Liquid templates with FluentEmail

    master

    Liquid templates are a more secure and faster alternative to Razor, especially when templates come from untrusted sources. Use .UsingTemplate(template, model) with the LiquidRenderer. You can configure LiquidRendererOptions with a FileProvider to resolve layout files.

    // Using Liquid templating package (or set using AddLiquidRenderer in services)
    
    // file provider is used to resolve layout files if they are in use
    var fileProvider = new PhysicalFileProvider(Path.Combine(someRootPath, "EmailTemplates"));
    var options = new LiquidRendererOptions
    {
        FileProvider = fileProvider
    };
    
    Email.DefaultRenderer = new LiquidRenderer(Options.Create(options));
    
    // template which utilizes layout
    var template = @"
    {% layout '_layout.liquid' %}
    Dear {{ Name }}, You are totally {{ Compliment }}.";
    
    var email = Email
        .From("bob@hotmail.com")
        .To("somedude@gmail.com")
        .Subject("woo nuget")
        .UsingTemplate(template, new ViewModel { Name = "Luke", Compliment = "Awesome" });
  8. Send emails synchronously or asynchronously

    master

    After defining the email, you can dispatch it using either .Send() (synchronous) or .SendAsync() (asynchronous).

    // Using Smtp Sender package (or set using AddSmtpSender in services)
    Email.DefaultSender = new SmtpSender();
    
    //send normally
    email.Send();
    
    //send asynchronously
    await email.SendAsync();
  9. Use an embedded template file

    master

    Load a template that is embedded as a resource in your assembly using .UsingTemplateFromEmbedded(resourceName, model, assembly).

    var email = new Email("bob@hotmail.com")
    	.To("benwholikesbeer@twitter.com")
    	.Subject("Hey cool name!")
    	.UsingTemplateFromEmbedded("Example.Project.Namespace.template-name.cshtml", 
    		new { Name = "Bob" }, 
    		TypeFromYourEmbeddedAssembly.GetType().GetTypeInfo().Assembly);