### Full Setup with Dependency Injection Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/ModuleOrganization.md Illustrates a comprehensive setup using dependency injection, including FluentEmail Core, SmtpSender, and RazorRenderer. ```csharp using FluentEmail.Core; using FluentEmail.Smtp; using FluentEmail.Razor; using Microsoft.Extensions.DependencyInjection; services .AddFluentEmail("noreply@example.com") .AddSmtpSender("smtp.example.com", 587, "user", "pass") .AddRazorRenderer(); var email = serviceProvider.GetRequiredService(); await email.To("...").Subject("...").Body("...").SendAsync(); ``` -------------------------------- ### Install FluentEmail Packages Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/REFERENCE.md Install the core FluentEmail package along with desired sender and renderer extensions using the .NET CLI. ```bash # Core with SMTP dotnet add package FluentEmail.Smtp # Or with SendGrid dotnet add package FluentEmail.SendGrid # And a template renderer dotnet add package FluentEmail.Razor ``` -------------------------------- ### Set Email Body Example Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Email.md Example demonstrating how to set both an HTML and a plain text body for an email. ```csharp email.Body("

Hello

", isHtml: true) .Body("Plain text body", isHtml: false); ``` -------------------------------- ### Add Core FluentEmail Package Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/README.md Install the core FluentEmail package using the .NET CLI. ```bash dotnet add package FluentEmail.Core ``` -------------------------------- ### Add FluentEmail Liquid Renderer Package Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/README.md Install the FluentEmail Liquid renderer package using the .NET CLI. ```bash dotnet add package FluentEmail.Liquid ``` -------------------------------- ### Instantiate and Configure SmtpClientOptions Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/types.md Example of creating and configuring SmtpClientOptions for Gmail. This setup is suitable for sending emails via Gmail's SMTP server. ```csharp var options = new SmtpClientOptions { Server = "smtp.gmail.com", Port = 587, UseSsl = true, RequiresAuthentication = true, User = "user@gmail.com", Password = "appPassword" }; var sender = new MailKitSender(options); ``` -------------------------------- ### Add FluentEmail SendGrid Sender Package Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/README.md Install the FluentEmail SendGrid sender package using the .NET CLI. ```bash dotnet add package FluentEmail.SendGrid ``` -------------------------------- ### SendGrid Configuration Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/DependencyInjection.md Example of configuring FluentEmail with SendGrid sender using dependency injection. ```APIDOC ### SendGrid Configuration ```csharp public void ConfigureServices(IServiceCollection services) { var sendGridApiKey = Configuration["SendGrid:ApiKey"]; services .AddFluentEmail("noreply@example.com") .AddLiquidRenderer() .AddSendGridSender(sendGridApiKey); } ``` ``` -------------------------------- ### Add FluentEmail Razor Renderer Package Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/README.md Install the FluentEmail Razor renderer package using the .NET CLI. ```bash dotnet add package FluentEmail.Razor ``` -------------------------------- ### Render Email Body from Template Example Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Email.md Example of using a template string with a model to generate the email body. ```csharp var model = new { Name = "John", Compliment = "Awesome" }; email.UsingTemplate("Dear @Model.Name, You are @Model.Compliment.", model); ``` -------------------------------- ### Liquid Template Syntax Example Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/configuration.md Demonstrates the syntax for Liquid templates, including variable access, loops, and layout includes. ```liquid

Hello {{ Name }}

Your order {{ OrderId }} is {{ Status }}

{% for item in Items %}
  • {{ item.Description }}
  • {% endfor %} {% layout '_layout.liquid' %} ``` -------------------------------- ### Priority Usage Example Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/types.md Shows how to set email priority using helper methods and how to check the current priority level. ```csharp email.HighPriority(); // Sets Priority = Priority.High email.LowPriority(); // Sets Priority = Priority.Low // Default is Priority.Normal var priority = email.Data.Priority; if (priority == Priority.High) Console.WriteLine("High priority!"); ``` -------------------------------- ### Add FluentEmail MailKit Sender Package Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/README.md Install the FluentEmail MailKit sender package using the .NET CLI. ```bash dotnet add package FluentEmail.MailKit ``` -------------------------------- ### Send Complete Email Example Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Email.md Demonstrates building an email with sender, recipients (To, CC, BCC), Reply-To, subject, HTML and plain text bodies, priority, attachments, tags, and custom headers. Requires `fileStream` to be defined. ```csharp var email = Email .From("sender@example.com", "Sender Name") .To("recipient@example.com", "Recipient Name") .CC("cc@example.com") .BCC("bcc@example.com") .ReplyTo("reply@example.com") .Subject("Welcome Email") .Body("

    Hello!

    Welcome to our service.

    ", isHtml: true) .PlaintextAlternativeBody("Hello!\n\nWelcome to our service.") .HighPriority() .Attach(new Attachment { Filename = "document.pdf", Data = fileStream, ContentType = "application/pdf" }) .Tag("welcome") .Header("X-Custom-Header", "CustomValue"); var response = await email.SendAsync(); ``` -------------------------------- ### Set Email Subject Example Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Email.md Example of how to set the subject line for an email using the Subject method. ```csharp email.Subject("Welcome to our service"); ``` -------------------------------- ### Attachment Usage Examples Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/types.md Demonstrates how to create and attach an Attachment object to an email, either directly or by specifying a filename. ```csharp var attachment = new Attachment { Filename = "invoice.pdf", Data = File.OpenRead("/path/to/invoice.pdf"), ContentType = "application/pdf" }; email.Attach(attachment); // Or from filename email.AttachFromFilename("/path/to/document.pdf", "application/pdf", "my-document.pdf"); ``` -------------------------------- ### SMTP Configuration Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/DependencyInjection.md Example of configuring FluentEmail with an SMTP sender using dependency injection. ```APIDOC ### SMTP Configuration ```csharp public void ConfigureServices(IServiceCollection services) { services .AddFluentEmail("noreply@example.com", "My Application") .AddRazorRenderer() .AddSmtpSender("smtp.example.com", 587, "username", "password"); } ``` ``` -------------------------------- ### Add FluentEmail Mailgun Sender Package Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/README.md Install the FluentEmail Mailgun sender package using the .NET CLI. ```bash dotnet add package FluentEmail.Mailgun ``` -------------------------------- ### Replace Renderer Template Syntax Example Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/configuration.md Shows how to use the Replace renderer with a template string and a model object for placeholder substitution. ```csharp var template = "Hello ##Name##! Your order ##OrderId## is ##Status##."; var model = new { Name = "John", OrderId = 123, Status = "Shipped" }; var result = Email.DefaultRenderer.Parse(template, model); // Result: "Hello John! Your order 123 is Shipped." ``` -------------------------------- ### Instantiate ReplaceRenderer Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Renderers.md Creates a new instance of the ReplaceRenderer. No specific setup is required beyond instantiation. ```csharp public ReplaceRenderer() ``` -------------------------------- ### Add FluentEmail Smtp Sender Package Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/README.md Install the FluentEmail SMTP sender package using the .NET CLI. ```bash dotnet add package FluentEmail.Smtp ``` -------------------------------- ### Initialize Email with Default Settings Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Email.md Creates a new email instance using default template rendering and email sending engines. This is the most basic way to start composing an email. ```csharp public Email() ``` -------------------------------- ### Add FluentEmail Mailtrap Sender Package Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/README.md Install the FluentEmail Mailtrap sender package using the .NET CLI. ```bash dotnet add package FluentEmail.Mailtrap ``` -------------------------------- ### Configure Liquid Renderer via DI Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/configuration.md Configure the Liquid renderer using a PhysicalFileProvider for template files and dependency injection. Includes SMTP sender setup. ```csharp var fileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), "EmailTemplates") ); services .AddFluentEmail("noreply@example.com") .AddLiquidRenderer(new LiquidRendererOptions { FileProvider = fileProvider }) .AddSmtpSender("localhost", 25); ``` -------------------------------- ### Add FluentEmail Graph Sender Package Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/README.md Install the FluentEmail Microsoft Graph sender package using the .NET CLI. ```bash dotnet add package FluentEmail.Graph ``` -------------------------------- ### Instantiate MailgunSender with EU Region Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/types.md Example of how to instantiate the MailgunSender, specifying the EU region for API requests. ```csharp var sender = new MailgunSender("mail.example.com", "key-xxx", MailGunRegion.EU); ``` -------------------------------- ### Using IFluentEmailFactory (Batch) Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/DependencyInjection.md Example of using IFluentEmailFactory to create and send multiple emails concurrently for batch operations. ```APIDOC ### Using IFluentEmailFactory (Batch) ```csharp public class BulkEmailService { private readonly IFluentEmailFactory _emailFactory; public BulkEmailService(IFluentEmailFactory emailFactory) { _emailFactory = emailFactory; } public async Task SendNewsletterAsync(List subscribers, string content) { var tasks = subscribers.Select(async sub => { var email = _emailFactory.Create(); var response = await email .To(sub.Email, sub.Name) .Subject("Monthly Newsletter") .Body(content, isHtml: true) .SendAsync(); return new { subscriber = sub.Email, successful = response.Successful }; }); var results = await Task.WhenAll(tasks); return results; } } ``` ``` -------------------------------- ### Liquid Template Example Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/REFERENCE.md Utilize Shopify Liquid syntax for untrusted templates. Offers a restricted environment and excellent performance without compilation. ```liquid

    Hello {{ Name }}

    {% for item in Items %}
  • {{ item.Description }}: {{ item.Price }}
  • {% endfor %} {% layout '_layout.liquid' %} ``` -------------------------------- ### Razor Template Syntax Example Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/configuration.md Illustrates the basic syntax for creating email templates using the Razor rendering engine, including model binding and loops. ```csharp var template = @"

    Hello @Model.Name

    Your order @Model.OrderId is @Model.Status

    @foreach (var item in Model.Items) {
  • @item.Description
  • } "; ``` -------------------------------- ### Replace Template Example Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/REFERENCE.md Employ simple placeholder replacement syntax (##PropertyName##) for basic variable substitution. Offers the fastest performance. ```plaintext Hello ##Name##, your order ##OrderId## is ##Status##. ``` -------------------------------- ### Using IFluentEmail (Single Email) Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/DependencyInjection.md Example of injecting and using a single IFluentEmail instance for sending an email via an API controller. ```APIDOC ### Using IFluentEmail (Single Email) ```csharp [ApiController] [Route("api/[controller]")] public class EmailController : ControllerBase { private readonly IFluentEmail _fluentEmail; public EmailController(IFluentEmail fluentEmail) { _fluentEmail = fluentEmail; } [HttpPost("send")] public async Task SendEmail(EmailRequest request) { var response = await _fluentEmail .To(request.Recipient) .Subject(request.Subject) .Body(request.Body, isHtml: true) .SendAsync(); if (response.Successful) return Ok(new { messageId = response.MessageId }); return BadRequest(new { errors = response.ErrorMessages }); } } ``` ``` -------------------------------- ### RazorRenderer HTML Template Example Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Renderers.md Demonstrates parsing an HTML formatted Razor template with a model, specifying isHtml: true. ```csharp var template = @"

    Welcome, @Model.Name

    Your order #@Model.OrderId is @Model.Status

    "; var model = new { Name = "Jane", OrderId = 123, Status = "Shipped" }; var result = renderer.Parse(template, model, isHtml: true); ``` -------------------------------- ### Configure Liquid Renderer with DI Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Renderers.md Add the Liquid renderer to FluentEmail services. This example demonstrates configuring a custom file provider for Liquid templates located in the 'EmailTemplates' directory. ```csharp public void ConfigureServices(IServiceCollection services) { var fileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), "EmailTemplates") ); services .AddFluentEmail("from@example.com") .AddLiquidRenderer(new LiquidRendererOptions { FileProvider = fileProvider }) .AddSmtpSender("localhost", 25); } ``` -------------------------------- ### SendResponse Usage Example Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/types.md Demonstrates how to check the success of an email send operation and display results or errors. Also shows instantiation of the generic SendResponse. ```csharp var response = await email.SendAsync(); if (response.Successful) { Console.WriteLine($"Sent with ID: {response.MessageId}"); } else { foreach (var error in response.ErrorMessages) Console.WriteLine($"Error: {error}"); } // Generic version with additional data SendResponse typedResponse = new SendResponse(); ``` -------------------------------- ### Razor Template Example Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/REFERENCE.md Use ASP.NET Razor syntax for complex, trusted templates. Requires full CLR access. ```razor

    Hello @Model.Name

    @foreach (var item in Model.Items) {
  • @item.Description: @item.Price.ToString("C")
  • } ``` -------------------------------- ### Configure Multiple Senders with Factory Pattern Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/configuration.md Implement a factory pattern to manage and switch between different email senders at runtime. This example shows how to use SendGrid and SMTP senders based on recipient domain. ```csharp public class SmartEmailService { private readonly IFluentEmailFactory _factory; private readonly SendGridSender _sendGridSender; private readonly SmtpSender _smtpSender; public SmartEmailService(IFluentEmailFactory factory, IConfiguration config) { _factory = factory; _sendGridSender = new SendGridSender(config["SendGrid:ApiKey"]); var smtpOptions = new SmtpClientOptions { Server = config["Smtp:Host"], Port = int.Parse(config["Smtp:Port"]), RequiresAuthentication = true, User = config["Smtp:User"], Password = config["Smtp:Password"] }; _smtpSender = new MailKitSender(smtpOptions); } public async Task SendViaPreferredSender(string recipient, string subject, string body) { var email = _factory.Create() .To(recipient) .Subject(subject) .Body(body); // Choose sender based on logic if (recipient.EndsWith("@premium-domain.com")) email.Sender = _sendGridSender; // Use SendGrid for premium else email.Sender = _smtpSender; // Use SMTP for others return await email.SendAsync(); } } ``` -------------------------------- ### Configure Razor Renderer via DI Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/configuration.md Configure the Razor renderer with a specified template root path using dependency injection. This example also includes SMTP sender configuration. ```csharp services .AddFluentEmail("noreply@example.com") .AddRazorRenderer("/app/EmailTemplates") .AddSmtpSender("localhost", 25); ``` -------------------------------- ### Basic FluentEmail Configuration Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/configuration.md Configure FluentEmail with a default sender address, name, renderer, and SMTP sender. This is a straightforward setup for basic email functionality. ```csharp public void ConfigureServices(IServiceCollection services) { services .AddFluentEmail("noreply@example.com", "My App") .AddRazorRenderer() .AddSmtpSender("localhost", 25); } ``` -------------------------------- ### Register FluentEmail Services Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/REFERENCE.md Register FluentEmail with dependency injection in ASP.NET Core. This example shows registration with Razor renderer and SMTP sender. Other sender and renderer options are commented out. ```csharp services .AddFluentEmail("defaultFromEmail@example.com", "Optional From Name") .AddRazorRenderer() // or .AddLiquidRenderer() .AddSmtpSender("host", port, "user", "password"); // or .AddSendGridSender(apiKey) // or .AddMailgunSender(domain, apiKey) // or .AddMailKitSender(options) // or .AddGraphSender(appId, tenantId, secret) ``` -------------------------------- ### FluentEmail with Dependency Injection Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/REFERENCE.md Shows how to configure FluentEmail with dependency injection in ASP.NET Core's Startup.cs and how to use it in a service. ```csharp // In Startup.ConfigureServices services .AddFluentEmail("noreply@example.com") .AddRazorRenderer() .AddSmtpSender("smtp.gmail.com", 587, "user", "password"); // In controller/service public class EmailService { private readonly IFluentEmail _email; public EmailService(IFluentEmail email) => _email = email; public async Task SendWelcomeAsync(string recipient) { var response = await _email .To(recipient) .Subject("Welcome") .Body("Welcome to our service!") .SendAsync(); } } ``` -------------------------------- ### Creating and Using Address Objects Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/types.md Demonstrates how to instantiate an Address object with a display name and email, and how to create a list of addresses for multiple recipients. This is commonly used with the `Email.To()` method. ```csharp var address = new Address("john@example.com", "John Doe"); var recipients = new List
    { new Address("user1@example.com", "User One"), new Address("user2@example.com", "User Two") }; email.To(recipients); ``` -------------------------------- ### Initialize Email with Custom Engines and From Address Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Email.md Creates a new email instance with specified template rendering and email sending engines, along with a custom 'from' email address and name. This provides full control over the email's composition and sending infrastructure. ```csharp public Email(ITemplateRenderer renderer, ISender sender, string emailAddress, string name = "") ``` -------------------------------- ### Configure FluentEmail with Dependency Injection Source: https://github.com/lukencode/fluentemail/blob/master/README.markdown Configures FluentEmail services in startup.cs, injecting IFluentEmail and IFluentEmailFactory. Requires AddRazorRenderer() and AddSmtpSender() or other packages. ```csharp public void ConfigureServices(IServiceCollection services) { services .AddFluentEmail("fromemail@test.test") .AddRazorRenderer() .AddSmtpSender("localhost", 25); } ``` -------------------------------- ### Configure Multiple Senders with DI and Factory Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/DependencyInjection.md Demonstrates setting up an SMTP sender via DI and then using IFluentEmailFactory and a specific sender instance in a service. ```csharp public void ConfigureServices(IServiceCollection services) { services .AddFluentEmail("noreply@example.com") .AddRazorRenderer() .AddSmtpSender("localhost", 25); } public class EmailService { private readonly IFluentEmailFactory _emailFactory; private readonly SendGridSender _sendGridSender; public EmailService(IFluentEmailFactory emailFactory) { _emailFactory = emailFactory; _sendGridSender = new SendGridSender(apiKey); } public async Task SendViaSmtp(IFluentEmail email) { // Uses the configured SMTP sender from DI return await email.SendAsync(); } public async Task SendViaSendGrid(IFluentEmail email) { // Use specific sender email.Sender = _sendGridSender; return await email.SendAsync(); } } ``` -------------------------------- ### Configure FluentEmail with DI Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/README.md Shows how to set up FluentEmail with dependency injection in ASP.NET Core, including adding a Razor renderer and a SendGrid sender. Replace 'your-api-key' with your actual SendGrid API key. ```csharp services .AddFluentEmail("noreply@example.com") .AddRazorRenderer() .AddSendGridSender("your-api-key"); ``` -------------------------------- ### Create IFluentEmail Instance Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/types.md Demonstrates how to create a new email instance using IFluentEmailFactory. This is commonly used within services that need to send multiple emails. ```csharp public interface IFluentEmailFactory { IFluentEmail Create(); } ``` ```csharp public class EmailService { private readonly IFluentEmailFactory _factory; public EmailService(IFluentEmailFactory factory) => _factory = factory; public async Task SendBatch(List addresses) { foreach (var address in addresses) { var email = _factory.Create(); await email.To(address).Subject("Hello").Body("Hi!").SendAsync(); } } } ``` -------------------------------- ### Initialize Email with Default Settings and From Address Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Email.md Creates a new email instance with default engines, pre-configuring the 'from' email address and optionally its associated name. Useful for setting a default sender identity. ```csharp public Email(string emailAddress, string name = "") ``` -------------------------------- ### Basic Email Sending with FluentEmail Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/REFERENCE.md Demonstrates setting default sender and renderer, then sending a simple HTML email. ```csharp using FluentEmail.Smtp; using FluentEmail.Razor; // Set default engines Email.DefaultRenderer = new RazorRenderer(); Email.DefaultSender = new SmtpSender("smtp.gmail.com", 587, "user@gmail.com", "password"); // Send email var response = await Email .From("sender@example.com", "Sender Name") .To("recipient@example.com", "Recipient Name") .Subject("Hello") .Body("

    Welcome!

    ", isHtml: true) .SendAsync(); if (response.Successful) Console.WriteLine($"Sent: {response.MessageId}"); ``` -------------------------------- ### Multiple Senders (with factory) Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/DependencyInjection.md Demonstrates setting up multiple email senders and how to use IFluentEmailFactory to select a specific sender. ```APIDOC ### Multiple Senders (with factory) ```csharp public void ConfigureServices(IServiceCollection services) { services .AddFluentEmail("noreply@example.com") .AddRazorRenderer() .AddSmtpSender("localhost", 25); } public class EmailService { private readonly IFluentEmailFactory _emailFactory; private readonly SendGridSender _sendGridSender; public EmailService(IFluentEmailFactory emailFactory) { _emailFactory = emailFactory; _sendGridSender = new SendGridSender(apiKey); } public async Task SendViaSmtp(IFluentEmail email) { // Uses the configured SMTP sender from DI return await email.SendAsync(); } public async Task SendViaSendGrid(IFluentEmail email) { // Use specific sender email.Sender = _sendGridSender; return await email.SendAsync(); } } ``` ``` -------------------------------- ### Create IFluentEmail Instance with Factory Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/DependencyInjection.md Demonstrates how to use IFluentEmailFactory to create independent email instances for batch sending. ```csharp public class EmailService { private readonly IFluentEmailFactory _emailFactory; public EmailService(IFluentEmailFactory emailFactory) { _emailFactory = emailFactory; } public async Task SendBatchEmails(List recipients) { foreach (var recipient in recipients) { var email = _emailFactory.Create() .To(recipient) .Subject("Hello") .Body("Welcome!"); await email.SendAsync(); } } } ``` -------------------------------- ### Email(string, string) Constructor Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Email.md Initializes a new email instance with a specified 'from' email address and an optional name, using default rendering and sending engines. ```APIDOC ## Email(string emailAddress, string name = "") ### Description Creates a new email instance with default settings and a specific from address. ### Parameters #### Path Parameters - **emailAddress** (string) - Required - Email address to send from - **name** (string) - Optional - Name associated with the from address ### Returns Email instance ``` -------------------------------- ### FluentEmail Core Functionality Imports Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/ModuleOrganization.md Import core FluentEmail functionality and models for building and sending emails. ```csharp // Core functionality using FluentEmail.Core; using FluentEmail.Core.Models; ``` -------------------------------- ### Send Email with Template from Disk Source: https://github.com/lukencode/fluentemail/blob/master/README.markdown Shows how to use a Razor template file located on disk to construct an email. ```csharp var email = Email .From("bob@hotmail.com") .To("somedude@gmail.com") .Subject("woo nuget") .UsingTemplateFromFile($"{Directory.GetCurrentDirectory()}/Mytemplate.cshtml", new { Name = "Rad Dude" }); ``` -------------------------------- ### Initialize SendGridSender with API Key Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Senders.md Creates a new instance of SendGridSender using your SendGrid API key. Optionally enable sandbox mode for testing. ```csharp public SendGridSender(string apiKey, bool sandBoxMode = false) ``` ```csharp var sender = new SendGridSender("SG.xxxxxxxxxxxxxxxxxxxxx"); ``` -------------------------------- ### Initialize Email with Custom Renderer and Sender Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Email.md Creates a new email instance, allowing you to specify custom implementations for template rendering and email sending. Use this when you need to integrate with specific libraries or services. ```csharp public Email(ITemplateRenderer renderer, ISender sender) ``` -------------------------------- ### Minimal Core Usage Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/ModuleOrganization.md Demonstrates the most basic usage of FluentEmail Core by setting a default sender and sending an email. ```csharp using FluentEmail.Core; Email.DefaultSender = new SaveToDiskSender("/emails"); await Email.From("...").To("...").Body("...").SendAsync(); ``` -------------------------------- ### Email Class - Static Factory and Main Methods Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/ModuleOrganization.md The Email class serves as the entry point for building emails. It provides static factory methods to initiate email creation and main methods to configure recipients, subject, body, attachments, and send the email. ```APIDOC ## Email Class ### Description Provides static factory methods to create an email instance and methods to configure and send emails. ### Entry Point `Email` class ### Static Factory Methods - `From(emailAddress, name)`: Creates a new email instance with the specified sender address and name. ### Main Methods - `To(emailAddress, name)`: Adds a recipient to the 'To' field. - `CC(emailAddress, name)`: Adds a recipient to the 'CC' field. - `BCC(emailAddress, name)`: Adds a recipient to the 'BCC' field. - `ReplyTo(emailAddress, name)`: Sets the 'Reply-To' address. - `Subject(subject)`: Sets the email subject. - `Body(body, isHtml)`: Sets the email body. `isHtml` indicates if the body is HTML. - `UsingTemplate(templateName, model)`: Uses a template to set the email body. - `Attach(filename, data, contentType)`: Attaches a file to the email. - `Send()`: Sends the email synchronously. - `SendAsync()`: Sends the email asynchronously. ``` -------------------------------- ### Email() Constructor Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Email.md Creates a new email instance with default settings, utilizing the default template renderer and sender. ```APIDOC ## Email() ### Description Creates a new email instance with default settings (default renderer and sender). ### Returns Email instance ``` -------------------------------- ### SaveToDiskSender Constructor Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Senders.md Initializes a new instance of the SaveToDiskSender class, specifying the directory where emails will be saved. ```APIDOC ## SaveToDiskSender(string directory) ### Description Creates a sender that saves emails to text files in the specified directory. ### Parameters #### Path Parameters - **directory** (string) - Required - Path to directory where emails will be saved ### Example ```csharp var sender = new SaveToDiskSender("/emails"); ``` ``` -------------------------------- ### SendGridSender Constructor Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Senders.md Initializes a new instance of the SendGridSender class with the provided API key and an optional sandbox mode setting. ```APIDOC ## SendGridSender(string apiKey, bool sandBoxMode = false) ### Description Creates a sender configured with a SendGrid API key. ### Parameters #### Path Parameters - **apiKey** (string) - Required - SendGrid API key - **sandBoxMode** (bool) - Optional - Enable sandbox mode for testing (emails not actually sent). Default: false ### Request Example ```csharp var sender = new SendGridSender("SG.xxxxxxxxxxxxxxxxxxxxx"); ``` ``` -------------------------------- ### Configure SendGrid Sender via DI Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/configuration.md Configure the SendGrid sender using dependency injection. Requires an API key retrieved from configuration. ```csharp var apiKey = Configuration["SendGrid:ApiKey"]; services .AddFluentEmail("noreply@example.com") .AddSendGridSender(apiKey); ``` -------------------------------- ### Configure Liquid Renderer Directly Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/configuration.md Set the Liquid renderer directly using Options.Create for LiquidRendererOptions, specifying a file provider for templates. ```csharp var options = Options.Create(new LiquidRendererOptions { FileProvider = new PhysicalFileProvider("/templates") }); Email.DefaultRenderer = new LiquidRenderer(options); ``` -------------------------------- ### Send Basic Email Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/README.md Demonstrates sending a simple HTML email using the fluent interface. Ensure the `SendAsync` method is awaited. ```csharp var response = await Email .From("sender@example.com") .To("recipient@example.com") .Subject("Hello") .Body("

    Welcome!

    ", isHtml: true) .SendAsync(); ``` -------------------------------- ### Send a Basic Email Source: https://github.com/lukencode/fluentemail/blob/master/README.markdown Demonstrates the basic usage of FluentEmail to send a simple email. ```csharp 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(); ``` -------------------------------- ### FluentEmail Renderer Imports Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/ModuleOrganization.md Import specific renderer implementations for templated emails. ```csharp // Renderers using FluentEmail.Razor; using FluentEmail.Liquid; ``` -------------------------------- ### Configure SendGrid Sender with DI Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/DependencyInjection.md Configures FluentEmail with Liquid rendering and a SendGrid sender using a provided API key. ```csharp public void ConfigureServices(IServiceCollection services) { var sendGridApiKey = Configuration["SendGrid:ApiKey"]; services .AddFluentEmail("noreply@example.com") .AddLiquidRenderer() .AddSendGridSender(sendGridApiKey); } ``` -------------------------------- ### MailKitSender Constructor with SmtpClientOptions Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Senders.md Creates a MailKitSender instance using provided SmtpClientOptions. Configure server, port, SSL, authentication, user, and password for your SMTP connection. ```csharp var options = new SmtpClientOptions { Server = "smtp.gmail.com", Port = 587, UseSsl = true, RequiresAuthentication = true, User = "user@gmail.com", Password = "password" }; var sender = new MailKitSender(options); ``` -------------------------------- ### Create Email From Address Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Email.md Creates a new Email instance and sets the 'from' property. Use this to initiate a new email with a specified sender address and optional display name. ```csharp public static IFluentEmail From(string emailAddress, string name = null) ``` ```csharp var email = Email.From("sender@example.com", "John Doe"); ``` -------------------------------- ### Email(ITemplateRenderer, ISender, string, string) Constructor Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Email.md Creates a new email instance with custom rendering and sending engines, and a specified 'from' email address with an optional name. ```APIDOC ## Email(ITemplateRenderer renderer, ISender sender, string emailAddress, string name = "") ### Description Creates a new email instance using the given engines and from address. ### Parameters #### Path Parameters - **renderer** (ITemplateRenderer) - Required - The template rendering engine - **sender** (ISender) - Required - The email sending implementation - **emailAddress** (string) - Required - Email address to send from - **name** (string) - Optional - Name associated with the from address ### Returns Email instance ``` -------------------------------- ### UsingTemplateFromFile Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Email.md Loads an email template from a file on disk and parses it with a provided model. Supports both HTML and plain text templates. ```APIDOC ## UsingTemplateFromFile(string filename, T model, bool isHtml = true) ### Description Loads a template from a file on disk and parses it with the provided model. ### Parameters #### Path Parameters - **filename** (string) - Required - Path to the template file - **model** (T) - Required - The model object for template parsing - **isHtml** (bool) - Optional - True if template renders HTML, false for plain text (Default: true) ### Returns IFluentEmail (fluent interface) ``` -------------------------------- ### Configure Mailgun Sender via DI Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/configuration.md Configure the Mailgun sender using dependency injection. Requires domain name, API key, and region. ```csharp services .AddFluentEmail("noreply@example.com") .AddMailgunSender("mail.example.com", apiKey, MailGunRegion.USA); ``` -------------------------------- ### Send Email with SmtpSender Source: https://github.com/lukencode/fluentemail/blob/master/README.markdown Demonstrates how to set the default sender to SmtpSender and send emails synchronously or asynchronously. ```csharp // Using Smtp Sender package (or set using AddSmtpSender in services) Email.DefaultSender = new SmtpSender(); //send normally email.Send(); //send asynchronously await email.SendAsync(); ``` -------------------------------- ### Email.From Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Email.md Creates a new Email instance and sets the 'from' property. This is a static method used to initiate email creation. ```APIDOC ## Email.From(string, string) ### Description Creates a new Email instance and sets the from property. ### Method Static ### Parameters #### Path Parameters - **emailAddress** (string) - Required - Email address of sender - **name** (string) - Optional - Display name of sender ### Returns IFluentEmail instance ### Example ```csharp var email = Email.From("sender@example.com", "John Doe"); ``` ``` -------------------------------- ### Basic Email Send with Error Handling Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/errors.md Demonstrates a basic try-catch block for handling exceptions during email sending and checking the success status of the response. ```csharp public async Task SendEmailAsync(EmailRequest request) { try { var response = await Email .From("sender@example.com") .To(request.Recipient) .Subject(request.Subject) .Body(request.Body, isHtml: true) .SendAsync(); if (response.Successful) { Logger.LogInformation($ ``` ```csharp Logger.LogError($ ``` ```csharp catch (Exception ex) { Logger.LogError(ex, "Email send exception"); return false; } } ``` -------------------------------- ### LiquidRenderer Constructor Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Renderers.md Initializes a new instance of the LiquidRenderer class with specified Liquid template options. ```APIDOC ## LiquidRenderer(IOptions) ### Description Creates a renderer with Liquid template options. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Signature `public LiquidRenderer(IOptions options)` ### Parameters - **options** (IOptions) - Required - Configuration options for Liquid rendering ### Returns LiquidRenderer instance ### Example ```csharp var options = Options.Create(new LiquidRendererOptions { FileProvider = new PhysicalFileProvider("/templates") }); var renderer = new LiquidRenderer(options); ``` ``` -------------------------------- ### Registering FluentEmail with SmtpSender Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/errors.md Shows the correct way to register FluentEmail services and configure the SmtpSender within the DI container's ConfigureServices method. ```csharp services.AddFluentEmail("from@example.com").AddSmtpSender("localhost", 25); ``` -------------------------------- ### LiquidRenderer Constructor Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Renderers.md Creates a LiquidRenderer instance with specified Liquid template options. Use this to configure file providers or other Liquid-specific settings. ```csharp public LiquidRenderer(IOptions options) ``` ```csharp var options = Options.Create(new LiquidRendererOptions { FileProvider = new PhysicalFileProvider("/templates") }); var renderer = new LiquidRenderer(options); ``` -------------------------------- ### Dependency Injection of IFluentEmail Source: https://github.com/lukencode/fluentemail/blob/master/README.markdown Shows how to take a dependency on IFluentEmail in a service class constructor for sending emails. ```csharp 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(); } } ``` -------------------------------- ### Create SaveToDiskSender Instance Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Senders.md Instantiate SaveToDiskSender to specify the directory where emails will be saved. This is useful for setting up the sender for testing. ```csharp public SaveToDiskSender(string directory) ``` ```csharp var sender = new SaveToDiskSender("/emails"); ``` -------------------------------- ### Send Batch Emails using IFluentEmailFactory Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/DependencyInjection.md Illustrates using IFluentEmailFactory within a service to send personalized emails to a list of subscribers concurrently. ```csharp public class BulkEmailService { private readonly IFluentEmailFactory _emailFactory; public BulkEmailService(IFluentEmailFactory emailFactory) { _emailFactory = emailFactory; } public async Task SendNewsletterAsync(List subscribers, string content) { var tasks = subscribers.Select(async sub => { var email = _emailFactory.Create(); var response = await email .To(sub.Email, sub.Name) .Subject("Monthly Newsletter") .Body(content, isHtml: true) .SendAsync(); return new { subscriber = sub.Email, successful = response.Successful }; }); var results = await Task.WhenAll(tasks); return results; } } ``` -------------------------------- ### Configure MailKit Sender via DI Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/configuration.md Configure the MailKit sender using dependency injection with detailed SMTP client options. ```csharp var options = new SmtpClientOptions { Server = "smtp.gmail.com", Port = 587, UseSsl = true, RequiresAuthentication = true, User = "user@gmail.com", Password = "appPassword" }; services .AddFluentEmail("noreply@example.com") .AddMailKitSender(options); ``` -------------------------------- ### Email(ITemplateRenderer, ISender) Constructor Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Email.md Creates a new email instance, allowing for custom template rendering and email sending implementations. ```APIDOC ## Email(ITemplateRenderer renderer, ISender sender) ### Description Creates a new email instance with overrides for rendering and sending engines. ### Parameters #### Path Parameters - **renderer** (ITemplateRenderer) - Required - The template rendering engine to use - **sender** (ISender) - Required - The email sending implementation to use ### Returns Email instance ``` -------------------------------- ### MailKitSender Constructor Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Senders.md Initializes a new instance of the MailKitSender class with the specified SMTP client options. ```APIDOC ## MailKitSender(SmtpClientOptions) ### Description Creates a sender with MailKit SMTP configuration options. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **smtpClientOptions** (SmtpClientOptions) - Required - Configuration for SMTP connection and authentication ### Example ```csharp var options = new SmtpClientOptions { Server = "smtp.gmail.com", Port = 587, UseSsl = true, RequiresAuthentication = true, User = "user@gmail.com", Password = "password" }; var sender = new MailKitSender(options); ``` ``` -------------------------------- ### Configure SendGrid with Environment Variables Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/configuration.md Retrieve SendGrid API key and SMTP password from environment variables to configure FluentEmail services. This is suitable for production environments where credentials should not be hardcoded. ```csharp var sendGridKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY"); var smtpPassword = Environment.GetEnvironmentVariable("SMTP_PASSWORD"); services .AddFluentEmail("noreply@example.com") .AddRazorRenderer() .AddSendGridSender(sendGridKey); ``` -------------------------------- ### MailgunSender Constructor Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Senders.md Creates a new instance of the MailgunSender with the provided Mailgun domain, API key, and optionally, the Mailgun region. ```APIDOC ## MailgunSender(string domainName, string apiKey, MailGunRegion mailGunRegion) ### Description Creates a sender configured with Mailgun credentials. ### Parameters #### Path Parameters - **domainName** (string) - Required - Mailgun domain (e.g., mail.example.com) - **apiKey** (string) - Required - Mailgun API key - **mailGunRegion** (MailGunRegion) - Optional - Default: MailGunRegion.USA - Region for Mailgun API endpoint ### Request Example ```csharp var sender = new MailgunSender("mail.example.com", "key-xxx", MailGunRegion.USA); ``` ``` -------------------------------- ### Use Dependency Injection for FluentEmail Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/REFERENCE.md Inject IFluentEmail for better testability and adherence to SOLID principles. Avoid static configurations for senders. ```csharp // Good services.AddFluentEmail("noreply@example.com") .AddSmtpSender(...); public class EmailService { public EmailService(IFluentEmail email) { } } // Avoid Email.DefaultSender = new SmtpSender(...); var email = new Email(); ``` -------------------------------- ### FluentEmailFactory Class and Create Method Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/ModuleOrganization.md The FluentEmailFactory class implements the IFluentEmailFactory interface and provides a method to create instances of IFluentEmail. ```APIDOC ## FluentEmailFactory Class ### Description Factory for creating email instances. ### Implements `IFluentEmailFactory` ### Methods - `Create()`: Creates and returns an instance of `IFluentEmail`. ``` -------------------------------- ### Configure SMTP Sender via DI Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/configuration.md Configure the SMTP sender using dependency injection. Ensure FluentEmail is added to your services. ```csharp services .AddFluentEmail("noreply@example.com") .AddSmtpSender("smtp.example.com", 587, "username", "password"); ``` -------------------------------- ### Configure Razor Renderer Directly Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/configuration.md Set the Razor renderer directly by creating an instance with the root path for template files. ```csharp Email.DefaultRenderer = new RazorRenderer("/app/EmailTemplates"); ``` -------------------------------- ### Configure Razor Renderer with DI Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Renderers.md Add the Razor renderer to FluentEmail services for template rendering. Ensure Razor syntax is used for templates. ```csharp public void ConfigureServices(IServiceCollection services) { services .AddFluentEmail("from@example.com") .AddRazorRenderer() .AddSmtpSender("localhost", 25); } ``` -------------------------------- ### SMTP Sender Configuration Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/ModuleOrganization.md Shows how to configure and use the SmtpSender for sending emails via an SMTP server. ```csharp using FluentEmail.Core; using FluentEmail.Smtp; Email.DefaultSender = new SmtpSender("smtp.example.com", 587, "user", "pass"); ``` -------------------------------- ### Register FluentEmail Services Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/DependencyInjection.md Use this method to register FluentEmail services in the dependency injection container. It sets up the default sender and renderer, and returns a builder for further configuration. ```csharp public static FluentEmailServicesBuilder AddFluentEmail( this IServiceCollection services, string defaultFromEmail, string defaultFromName = "") ``` ```csharp public void ConfigureServices(IServiceCollection services) { services .AddFluentEmail("noreply@example.com", "MyApp") .AddRazorRenderer() .AddSmtpSender("smtp.gmail.com", 587, "user@gmail.com", "password"); } ``` -------------------------------- ### Configure SendGrid Sender Directly Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/configuration.md Instantiate and set the SendGrid sender directly. The sandbox mode can be enabled to test without sending actual emails. ```csharp var sender = new SendGridSender(apiKey, sandBoxMode: false); Email.DefaultSender = sender; ``` -------------------------------- ### FluentEmail Dependency Injection Imports Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/ModuleOrganization.md Import extensions for integrating FluentEmail with Microsoft's Dependency Injection container. ```csharp // Dependency Injection using Microsoft.Extensions.DependencyInjection; ``` -------------------------------- ### Configure SaveToDiskSender for Testing Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/configuration.md Integrate SaveToDiskSender to save outgoing emails as files for testing or development purposes. Specify the directory where emails should be stored. ```csharp services .AddFluentEmail("noreply@example.com") .AddRazorRenderer() .AddSender(new SaveToDiskSender("/path/to/emails")); ``` ```csharp Email.DefaultSender = new SaveToDiskSender("./emails"); ``` -------------------------------- ### Instantiate MailgunSender Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/Senders.md Creates a new MailgunSender instance using your Mailgun domain name, API key, and optionally a specific MailGun region. ```csharp public MailgunSender(string domainName, string apiKey, MailGunRegion mailGunRegion = MailGunRegion.USA) ``` ```csharp var sender = new MailgunSender("mail.example.com", "key-xxx", MailGunRegion.USA); ``` -------------------------------- ### Send Single Email using DI Source: https://github.com/lukencode/fluentemail/blob/master/_autodocs/api-reference/DependencyInjection.md Shows how to inject IFluentEmail directly into a controller and use it to send a single email. ```csharp [ApiController] [Route("api/[controller]")] public class EmailController : ControllerBase { private readonly IFluentEmail _fluentEmail; public EmailController(IFluentEmail fluentEmail) { _fluentEmail = fluentEmail; } [HttpPost("send")] public async Task SendEmail(EmailRequest request) { var response = await _fluentEmail .To(request.Recipient) .Subject(request.Subject) .Body(request.Body, isHtml: true) .SendAsync(); if (response.Successful) return Ok(new { messageId = response.MessageId }); return BadRequest(new { errors = response.ErrorMessages }); } } ```