Why FluentEmail?
FluentEmail simplifies the process of sending emails by providing a clean and fluent API. It supports various email sending providers, including SMTP, SendGrid, and Mailgun. With FluentEmail, you can quickly set up and send emails without getting bogged down by boilerplate code.
Getting Started
Step 1: Create a New .NET Console Application
First, create a new .NET console application if you don't already have one:
dotnet new console -n FluentEmailDemo
cd FluentEmailDemo
Step 2: Install FluentEmail NuGet Packages
Next, install the necessary FluentEmail packages. For this example, we'll use the SMTP sender:
dotnet add package FluentEmail.Core
dotnet add package FluentEmail.Smtp
Step 3: Configure FluentEmail
In your Program.cs file, configure FluentEmail with your SMTP settings. Replace the placeholder values with your actual SMTP server details.
Set environment variables in your development environment:
export EMAIL_USERNAME="your-email@example.com"
export EMAIL_PASSWORD="your-email-password"
using System;
using System.Net;
using System.Net.Mail;
using FluentEmail.Core;
using FluentEmail.Smtp;
namespace FluentEmailDemo
{
class Program
{
static async Task Main(string[] args)
{
var sender = new SmtpSender(() => new SmtpClient("smtp.your-email-provider.com")
{
UseDefaultCredentials = false,
Credentials = new NetworkCredential(
Environment.GetEnvironmentVariable("EMAIL_USERNAME"),
Environment.GetEnvironmentVariable("EMAIL_PASSWORD")),
EnableSsl = true,
Port = 587
});
Email.DefaultSender = sender;
var email = await Email
.From("your-email@example.com")
.To("recipient@example.com", "Recipient Name")
.Subject("Test Email")
.Body("This is a test email sent using FluentEmail.", false)
.SendAsync();
if (email.Successful)
{
Console.WriteLine("Email sent successfully!");
}
else
{
Console.WriteLine("Failed to send email. Errors: " + string.Join(", ", email.ErrorMessages));
}
}
}
}
Step 4: Run the Application
Run the application to send the email:
dotnet run
Conclusion
FluentEmail provides a streamlined way to handle email sending in .NET applications. With its fluent API and support for multiple email providers, it takes the hassle out of email communication. Whether you're sending simple notifications or complex email campaigns, FluentEmail has you covered.
By following this guide, you should now be able to set up and use FluentEmail in your .NET projects. Happy coding!
Top comments (0)