.NET HELP

FluentEmail C# (How It Works For Developers)

Published August 13, 2024
Share:

In today's digital age, email remains a cornerstone of communication for businesses and individuals. Integrating robust email functionality into ASP.NET Core applications is essential for automating notifications, sending newsletters, and facilitating customer interactions. FluentEmail, a powerful library for .NET, combined with Mailgun API keys, offers developers a seamless solution to enhance email capabilities with reliability and scalability. Later in this article, we will also look at the IronPDF Library on ironsoftware.com to generate and manage PDF documents.

Introduction

FluentEmail simplifies the process of sending multiple emails programmatically within .NET applications. It provides an intuitive and fluent interface for configuring email messages, managing attachments, and handling recipient lists. This library abstracts away the complexities of SMTP configuration and supports multiple template renderer providers and test email service providers, including Mailgun.

FluentEmail.NET is a popular library in the .NET Core ecosystem for sending emails, and it supports Razor email templates as well as Liquid templates for creating email bodies dynamically. Using Razor template renderer with FluentEmail.NET allows you to leverage the power of Razor syntax to create well-formatted, dynamic email content and resolve layout files.

Here’s a basic guide on how to use FluentEmail.NET with ASP.NET Core Razor templates.

Step 1: Install FluentEmail

First, you need to install the FluentEmail package and the Razor templates renderer package by either using the Install-Package command or the .NET add package command:

Install-Package FluentEmail.Core
or
dotnet add package FluentEmail.Core
Install-Package FluentEmail.Razor
or
dotnet add package FluentEmail.Razor
Install-Package FluentEmail.Core
or
dotnet add package FluentEmail.Core
Install-Package FluentEmail.Razor
or
dotnet add package FluentEmail.Razor
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Step 2: Create a Razor Template

Create a Razor template for your email body. This can be a `.cshtml` file containing HTML and valid Razor code syntax. For example, create a file named `EmailTemplate.cshtml`:

@model YourNamespace.EmailViewModel
<!DOCTYPE html>
<html>
<head>
    <title>Email Template</title>
</head>
<body>
    <h1>Hello, @Model.Name!</h1>
    <p>This is a sample email template.</p>
</body>
</html>
// string template code with very basic defaults
@model YourNamespace.EmailViewModel
<!DOCTYPE html>
<html>
<head>
    <title>Email Template</title>
</head>
<body>
    <h1>Hello, @Model.Name!</h1>
    <p>This is a sample email template.</p>
</body>
</html>
// string template code with very basic defaults
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Make sure to replace `YourNamespace.EmailViewModel` with the actual namespace and class name of your view model or just the domain model that you will pass to this template.

Step 3: Set Up FluentEmail with Razor Renderer

Configure FluentEmail to use the Razor renderer and provide the necessary dependencies:

using FluentEmail.Core;
using FluentEmail.Razor;
public void ConfigureFluentEmail()
{
    FluentEmail.Core.Email.DefaultRenderer = new RazorRenderer();
    // Set up email smtp sender address
    Email.DefaultSender = new SmtpSender(new SmtpClient("smtp.yourserver.com"));
}
using FluentEmail.Core;
using FluentEmail.Razor;
public void ConfigureFluentEmail()
{
    FluentEmail.Core.Email.DefaultRenderer = new RazorRenderer();
    // Set up email smtp sender address
    Email.DefaultSender = new SmtpSender(new SmtpClient("smtp.yourserver.com"));
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Step 4: Render and Send Email

In your application code, render the Razor template with the desired model and send the email:

using FluentEmail.Core;
using FluentEmail.Razor;
public void SendEmail()
{
// layout var template
    var template = "EmailTemplate.cshtml"
    var email = Email
        .From("sender@example.com") // default sendfrom address
        .To("recipient@example.com")
        .Subject("Sample Email");
    var model = new EmailViewModel { Name = "John Doe" };
    email.UsingTemplateFromFile(template, model);
    email.Send();
}
using FluentEmail.Core;
using FluentEmail.Razor;
public void SendEmail()
{
// layout var template
    var template = "EmailTemplate.cshtml"
    var email = Email
        .From("sender@example.com") // default sendfrom address
        .To("recipient@example.com")
        .Subject("Sample Email");
    var model = new EmailViewModel { Name = "John Doe" };
    email.UsingTemplateFromFile(template, model);
    email.Send();
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Ensure that `EmailViewModel` matches the model defined in your Razor template (`EmailTemplate.cshtml`). This model should contain properties you reference in your Razor template (`@Model.Name`, for example).

Integrating Mailgun API Keys

Mailgun is a popular email service provider known for its reliability, deliverability, and rich features. By integrating Mailgun API keys with FluentEmail, developers can leverage Mailgun's infrastructure to send emails efficiently and securely.

Steps to Integrate Mailgun API Keys with FluentEmail

  1. Obtain Mailgun API Keys:

    • Sign up for a Mailgun account if you haven't already.

    • Navigate to the Mailgun Dashboard and create a new API key. Provide a description.

FluentEmail C# (How It Works For Developers): Figure 1 - Mailgun

  1. Install FluentEmail Package:

    Use NuGet Package Manager or Package Manager Console in Visual Studio to install FluentMail:

    Install-Package FluentEmail.Mailgun
    Install-Package FluentEmail.Mailgun
    IRON VB CONVERTER ERROR developers@ironsoftware.com
    VB   C#

or from Visual Studio

FluentEmail C# (How It Works For Developers): Figure 2 - FluentEmail.Mailgun

  1. Configure FluentEmail with Mailgun API Keys:

Set up FluentEmail to use Mailgun as the email service provider or SMTP sender by configuring your API keys:

using FluentEmail.Core;
using FluentEmail.Mailgun;
var sender = new MailgunSender("your-domain.com", "your-mailgun-api-key");
Email.DefaultSender = sender;
using FluentEmail.Core;
using FluentEmail.Mailgun;
var sender = new MailgunSender("your-domain.com", "your-mailgun-api-key");
Email.DefaultSender = sender;
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#
  1. Compose and Send Emails:

    Use FluentEmail's fluent interface to compose and send emails:

    var email = Email
        .From("sender@example.com")
        .To("recipient@example.com")
        .Subject("Your Subject Here")
        .Body("Hello, this is a test email sent via FluentMail and Mailgun!")
        .Send();
    var email = Email
        .From("sender@example.com")
        .To("recipient@example.com")
        .Subject("Your Subject Here")
        .Body("Hello, this is a test email sent via FluentMail and Mailgun!")
        .Send();
    IRON VB CONVERTER ERROR developers@ironsoftware.com
    VB   C#
  2. Advanced Configuration:

    • Customize email settings such as attachments, HTML formatting, CC/BCC recipients, and email headers using FluentEmail's fluent API.

Benefits of Using FluentEmail with Mailgun

  • Simplicity: FluentEmail abstracts away the complexities of SMTP configuration, making it easy to send emails with minimal setup.
  • Reliability: Leveraging Mailgun's infrastructure ensures high deliverability rates and robust email handling capabilities.
  • Scalability: Scale your email-sending needs effortlessly with Mailgun's scalable infrastructure, suitable for both small-scale applications and enterprise-level solutions.
  • Rich Features: Take advantage of Mailgun's features such as tracking, analytics, and advanced email validation to optimize your email campaigns.

Introduction to IronPDF

FluentEmail C# (How It Works For Developers): Figure 3 - IronPDF

IronPDF is a Node.js PDF library that allows to generate, manage, and extract content from PDF documents in .NET projects. Here are some key features:

  1. HTML to PDF Conversion:

    • Convert HTML, CSS, and JavaScript content to PDF Documents.

    • Chrome Rendering Engine for pixel-perfect PDFs.

    • Generate PDFs from URLs, HTML files, or HTML strings as input.
  2. Image and Content Conversion:

    • Convert images to and from PDFs.

    • Extract text and images from existing PDF documents.

    • Support for various image formats like JPG, PNG, etc.
  3. Editing and Manipulation:

    • Set properties, security, and permissions for PDFs.

    • Add digital signatures.

    • Edit metadata and revision history.

Generate PDF document Using IronPDF And FluentEmail .NET with Mailgun sender

To start with, create a Console application using Visual Studio as below.

FluentEmail C# (How It Works For Developers): Figure 4 - Console App

Provide Project Name.

FluentEmail C# (How It Works For Developers): Figure 5 - Project Configuration

Provide .NET Version.

FluentEmail C# (How It Works For Developers): Figure 6 - Target Framework

Install IronPDF package.

FluentEmail C# (How It Works For Developers): Figure 7 - IronPDF

Install FluentEmail Mailgun.

FluentEmail C# (How It Works For Developers): Figure 8 - FluentEmail.Mailgun

To receive email messages in the free trial, the receiver email should be registered in the dashboard on the Mailgun Registration Dashboard as shown below.

FluentEmail C# (How It Works For Developers): Figure 9 - Mailgun Dashboard

using FluentEmail.Core;
using FluentEmail.Mailgun;
namespace CodeSample
{
    public static class FluentMailDemo
    {
        public static void Execute()
        {
            // Instantiate Renderer
            var renderer = new ChromePdfRenderer();
            var content = "<h1>Demo FluentEmail with Mailgun and IronPDF</h1>";
            content += "<h2>Create MailgunSender</h2>";
            content += "<p>1. get API key from app.mailgun.com</p>";
            var domain = "sandboxe26ac376696246a4ad6ceedcfc2b5639.mailgun.org";
            var sender = new MailgunSender(domain, "8b50c68f19de7ddbb129464e129e9d61-6fafb9bf-e36ab713");
            Email.DefaultSender = sender;
            content += "<h2>Prepare Email</h2>";
            content += $"<p>Sender: Santosh@{domain}</p>";
            content += $"<p>Receiver: karanamsantosh99@gmail.com</p>";
            content += $"<p>Subject: Checkout the New Awesome IronPDF Library from IronSoftware</p>";
            content += $"<p>Body: IronPDF is the leading C# PDF library for generating & editing PDFs. It has friendly API and allows developers to rapidly deliver professional, high quality PDFs from HTML in .NET projects.</p>";
            var pdf = renderer.RenderHtmlAsPdf(content);
            // Export to a file or Stream
            pdf.SaveAs("AwesomeFluentEmailAndIron.pdf");
            var email = Email.From("santosh@"+domain)
                .To("karanamsantosh99@gmail.com")
                .Subject("Checkout the New Awesome IronPDF Library from IronSoftware")
                .Body("IronPDF is the leading C# PDF library for generating & editing PDFs. It has friendly API and allows developers to rapidly deliver professional, high quality PDFs from HTML in .NET projects.")
                .Attach(new FluentEmail.Core.Models.Attachment() { Data=File.OpenRead("AwesomeFluentEmailAndIron.pdf"), Filename="AwesomeFluentEmailAndIron.pdf", ContentType="application/pdf" })
                .Send();
            Console.WriteLine($"Is Send Success:{email.Successful}");
        }
    }
}
using FluentEmail.Core;
using FluentEmail.Mailgun;
namespace CodeSample
{
    public static class FluentMailDemo
    {
        public static void Execute()
        {
            // Instantiate Renderer
            var renderer = new ChromePdfRenderer();
            var content = "<h1>Demo FluentEmail with Mailgun and IronPDF</h1>";
            content += "<h2>Create MailgunSender</h2>";
            content += "<p>1. get API key from app.mailgun.com</p>";
            var domain = "sandboxe26ac376696246a4ad6ceedcfc2b5639.mailgun.org";
            var sender = new MailgunSender(domain, "8b50c68f19de7ddbb129464e129e9d61-6fafb9bf-e36ab713");
            Email.DefaultSender = sender;
            content += "<h2>Prepare Email</h2>";
            content += $"<p>Sender: Santosh@{domain}</p>";
            content += $"<p>Receiver: karanamsantosh99@gmail.com</p>";
            content += $"<p>Subject: Checkout the New Awesome IronPDF Library from IronSoftware</p>";
            content += $"<p>Body: IronPDF is the leading C# PDF library for generating & editing PDFs. It has friendly API and allows developers to rapidly deliver professional, high quality PDFs from HTML in .NET projects.</p>";
            var pdf = renderer.RenderHtmlAsPdf(content);
            // Export to a file or Stream
            pdf.SaveAs("AwesomeFluentEmailAndIron.pdf");
            var email = Email.From("santosh@"+domain)
                .To("karanamsantosh99@gmail.com")
                .Subject("Checkout the New Awesome IronPDF Library from IronSoftware")
                .Body("IronPDF is the leading C# PDF library for generating & editing PDFs. It has friendly API and allows developers to rapidly deliver professional, high quality PDFs from HTML in .NET projects.")
                .Attach(new FluentEmail.Core.Models.Attachment() { Data=File.OpenRead("AwesomeFluentEmailAndIron.pdf"), Filename="AwesomeFluentEmailAndIron.pdf", ContentType="application/pdf" })
                .Send();
            Console.WriteLine($"Is Send Success:{email.Successful}");
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Code Explanation

  1. FluentEmail and Mailgun Integration:

    • FluentEmail.Core: Provides a fluent interface for composing and sending emails.

    • FluentEmail.Mailgun: Enables integration with Mailgun for email delivery.
  2. ChromePdfRenderer:

    • This is assumed to be an instance of ChromePdfRenderer from the IronPDF library, used to render HTML content into a PDF document.
  3. Content Preparation:

    • HTML content (content) is prepared, including details about IronPDF. This content is used both for generating the PDF (renderer.RenderHtmlAsPdf(content)) and for the email body.
  4. MailgunSender Setup:

    • MailgunSender is initialized with Mailgun API credentials (domain and API key). The Email.DefaultSender is set to this sender, ensuring all subsequent emails use Mailgun for delivery.
  5. PDF Generation and Attachment:

    • The HTML content (content) is rendered into a PDF (pdf) using IronPDF's RenderHtmlAsPdf method.

    • The generated PDF is saved as "AwesomeFluentEmailAndIron.pdf".
  6. Email Composition and Sending:

    • An email is composed using FluentEmail's fluent API:

      • From address is set using the sender's domain.

      • To address is set to.

      • The subject and body of the email are defined.

      • The PDF file "AwesomeFluentEmailAndIron.pdf" is attached to the email.
    • The email is sent using .Send(), and the success status (email.Successful) is printed to the console.
  7. Console Output:

    • After attempting to send the email, the code outputs whether the email was sent successfully (Is Send Success: true/false).

Output Email Message

FluentEmail C# (How It Works For Developers): Figure 10 - Email Output

Attached PDF

FluentEmail C# (How It Works For Developers): Figure 11 - PDF Output

IronPDF Licensing

IronPDF package requires license to run and generate the PDF. Add below code at the start of the application before the package is accessed.

IronPdf.License.LicenseKey = "IRONPDF-LICENSE-KEY";
IronPdf.License.LicenseKey = "IRONPDF-LICENSE-KEY";
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Trial License is available at IronPDF Licensing and Trial.

Conclusion

FluentEmail, combined with Mailgun API keys, empowers .NET developers to streamline email functionality within their applications. Whether sending transactional emails, newsletters, or notifications, this integration ensures reliability, scalability, and ease of use. By abstracting the complexities of email delivery, FluentEmail allows developers to focus on building robust applications while leveraging Mailgun's powerful email infrastructure. Embrace the power of FluentEmail and Mailgun to enhance your email communication capabilities in .NET applications today.
IronPDF on the other hand is a robust C# library for creating, editing, and converting PDF documents within .NET applications. It excels in HTML to PDF conversion, offers comprehensive PDF manipulation capabilities, and integrates seamlessly with .NET frameworks, providing secure and versatile PDF handling solutions.

< PREVIOUS
Entity Framework Core (How It Works For Developers)
NEXT >
LazyCache C# (How It Works For Developers)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,622,374 View Licenses >