Introduction
In modern web applications, sending recurring emails is a common requirement for tasks such as notifications, reminders, or scheduled reports. Hangfire is a popular library in the .NET ecosystem that provides a simple way to perform background processing tasks, including sending emails, in .NET applications. With the introduction of .NET Core Minimal APIs, building lightweight and efficient web applications has become even easier. In this article, we'll explore how to use Hangfire within a .NET Core Minimal API to send recurring emails.
Prerequisites
- Basic understanding of C# and .NET Core
- .NET 6 SDK or later installed
- Visual Studio Code or any text editor of your choice
Setting up the Project: First, let's create a new .NET Core Minimal API project. Open your terminal or command prompt and run the following commands:
dotnet new web -n EmailScheduler
cd EmailScheduler
Now, let's install the necessary NuGet packages:
dotnet add package Hangfire.AspNetCore
dotnet add package Hangfire.SqlServer
Hangfire.AspNetCore provides integration with ASP.NET Core, while Hangfire.SqlServer provides support for SQL Server storage for Hangfire.
Configuring Hangfire: Next, let's configure Hangfire in our application. Open the Program.cs file and update it as follows:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Hangfire;
using Hangfire.SqlServer;
var builder = WebApplication.CreateBuilder(args);
// Add Hangfire services
builder.Services.AddHangfire(config =>
{
config.UseSqlServerStorage(builder.Configuration.GetConnectionString("HangfireConnection"));
});
var app = builder.Build();
// Configure Hangfire middleware
app.UseHangfireServer();
app.UseHangfireDashboard();
app.MapGet("/", () => "Hangfire is running!");
app.Run();
In the above code
- We added Hangfire services using the AddHangfire method and configured it to use SQL Server storage.
- We used UseHangfireServer to enable the Hangfire server for processing background jobs.
- We used UseHangfireDashboard to enable the Hangfire dashboard for monitoring and managing background jobs.
- Finally, we mapped a GET endpoint to confirm that Hangfire is running.
Creating Email Sending Job: Now, let's create a background job to send emails. Create a new folder named Jobs in the project directory, and inside that folder, create a new C# file named EmailSenderJob.cs with the following content:
using System;
using Hangfire;
public class EmailSenderJob
{
public static void SendEmail(string email)
{
Console.WriteLine($"Sending email to {email} at {DateTime.Now}");
// Add email sending logic here
}
}
This is a simple job that logs a message indicating that an email is being sent. Replace the placeholder comment with the actual logic to send emails.
Scheduling Recurring Emails: Now, let's schedule this job to run periodically. Update the Program.cs file as follows:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Hangfire;
using Hangfire.SqlServer;
var builder = WebApplication.CreateBuilder(args);
// Add Hangfire services
builder.Services.AddHangfire(config =>
{
config.UseSqlServerStorage(builder.Configuration.GetConnectionString("HangfireConnection"));
});
var app = builder.Build();
// Configure Hangfire middleware
app.UseHangfireServer();
app.UseHangfireDashboard();
// Schedule recurring job
RecurringJob.AddOrUpdate(() => EmailSenderJob.SendEmail("[email protected]"), Cron.Hourly);
app.MapGet("/", () => "Hangfire is running!");
app.Run();
In the above code, we used RecurringJob.AddOrUpdate method to schedule the SendEmail method of the EmailSenderJob class to run hourly. You can customize the cron expression as per your requirements.
Database Connection String: Make sure to add the connection string for Hangfire SQL Server storage in your appsettings.json file:
{
"ConnectionStrings": {
"HangfireConnection": "YourConnectionStringHere"
}
}
Replace "YourConnectionStringHere" with the actual connection string for your SQL Server instance.
Running the Application: Now, you can run your application using the following command:
dotnet run
Visit http://localhost:5000/hangfire in your browser to access the Hangfire dashboard and monitor the scheduled jobs.
Conclusion: In this article, we explored how to use Hangfire within a .NET Core Minimal API to send recurring emails. Hangfire provides a convenient way to schedule and execute background jobs, making it easy to handle tasks like sending emails in the background. By integrating Hangfire with .NET Core Minimal APIs, you can build lightweight and efficient web applications with background processing capabilities.
😊Please consider liking and following me for more articles and if you find this content helpful.👍