In this blog, we will explore how to use Hangfire to efficiently schedule emails.
What is Hangfire?
Hangfire is an open-source framework that allows you to create, process, and manage background jobs with ease.
It supports a wide range of background activities, including short-term and long-term, CPU and I/O heavy, one-time, and recurring.
Installation
To get started with Hangfire, follow these simple installation steps:
- Install the following packages
dotnet add package Hangfire.Core
dotnet add package Hangfire.SqlServer
dotnet add package Microsoft.Data.SqlClient
2. After installing the necessary packages, you’ll need to configure Hangfire in the ‘program.cs’ file as shown below,
builder.Services.AddHangfire(configuration => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseSqlServerStorage(builder.Configuration.GetConnectionString("DbConnection"), new SqlServerStorageOptions
{
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero,
UseRecommendedIsolationLevel = true,
DisableGlobalLocks = true
}));
builder.Services.AddHangfireServer();
3. Upon running your solution, the necessary tables will be created in the database as given below,
Scheduling Emails with Hangfire
For scheduling the email, We have to create an endpoint called “ScheduleEmail” in .NET web API as shown below,
[HttpPost]
[Route("ScheduleEmail")]
public string ScheduleEmail(DateTime dateTime)
{
var jobId = BackgroundJob.Schedule(() => emailService.SendEmail(), dateTime);
return jobId;
}
Here, we get the date and time to schedule the email based on the user’s input.
The ‘SendEmail()’ method contains the email content and configuration for sending the email.
Here’s a simplified example of the ‘SendEmail()’ method:
public async Task<string> SendEmail()
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
oMail.From = "Sender mail id";
oMail.To = "Receiver mail id";
oMail.Subject = "test email" + DateTime.Now;
oMail.Date = DateTime.Now;
oMail.TextBody = "Test email body";
SmtpServer server = new SmtpServer("smtp.gmail.com");
server.User = "username";
server.Password = "password";
server.Port = 25;
server.ConnectType = SmtpConnectType.ConnectSSLAuto;
SmtpClient oSmtp = new SmtpClient();
oSmtp.SendMail(server, oMail);
return "email was sent successfully!";
}
catch (Exception)
{
throw;
}
}
In the request, you provide the desired date and time for sending the email.
When you execute, Hangfire will handle the scheduling for you.
Conclusion
We’ve seen how Hangfire simplifies email scheduling in.NET in this blog. Its simple interface and permanent storage make it a good choice for automating this activity and boosting email reliability and scalability.
No Comment! Be the first one.