Search code examples
asp.net-coreasp.net-web-apientity-framework-corehangfire

ASP.NET CORE Web API - Payment notification Email Scheduler using Hangfire Cron Job


I have a Payment Application in ASP.NET Core-6 Web API Entity Framework. I have this model:

Payment:

public class Payment
{
    public Guid Id { get; set; }
    public string ReferenceNumber { get; set; }
    public string Email { get; set; }
    public DateTime TransactionDate { get; set; }
    public DateTime? DueDate { get; set; }
    public decimal Amount { get; set; }
}

EmailSettings:

public class EmailSettings
{
    public string Username { get; set; }
    public string Password { get; set; }
    public string DisplayName { get; set; }
    public string Host { get; set; }
    public int Port { get; set; }
}

EmailService:

public async Task<string> SendEmailAsync(List<string> ToEmailName, string Subject, EventModel Data)
{
    _mailResponse = string.Empty;

    using (SmtpClient smtpClient = new SmtpClient(_mailConfig.Host, _mailConfig.Port))
    {
        smtpClient.UseDefaultCredentials = true;
        smtpClient.Credentials = new NetworkCredential(_mailConfig.Username, _mailConfig.Password);
        smtpClient.EnableSsl = true;
        smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtpClient.SendCompleted += new SendCompletedEventHandler((object sender, AsyncCompletedEventArgs e) =>
        {
            _mailResponse = (e.Error != null || e.Cancelled != false) ? "failure" : "success";
        });

        MailMessage message = new MailMessage
        {
            From = new MailAddress(_mailConfig.Username, _mailConfig.DisplayName),
            Subject = Subject,
            SubjectEncoding = Encoding.UTF8,
            BodyEncoding = Encoding.UTF8,
            HeadersEncoding = Encoding.UTF8,
            IsBodyHtml = true,
            Body = GetEmailContent(Subject, Data),
            Priority = MailPriority.High
        };
        foreach (string EmailName in ToEmailName)
        {
            message.To.Add(new MailAddress(EmailName));
        }

        await smtpClient.SendMailAsync(message);
    }

    return _mailResponse;
}

I am using HangFire.

I want the application to run a schedule using HangFire, and iterate the Payment Model using ReferenceNumber and DueDate. Then send email notification to the affected Email, 14 days to the DueDate. Reminding the affected users that his payment should be done on the DueDate

How do I achieve this?


Solution

  • This can be done by scheduling notification directly based on DueDate - 14 days (or current date if that is less than 14 days away). Also probably you would need to some extra check to your notification to see if that has already been paid before sending a reminder.

    BackgroundJob.Schedule(
        () => NotficationService.SendPaymentNotificationEmail(Payment.Id),
        TimeSpan.FromDays(DueDate.AddDays(-14)));
    

    Reference: https://docs.hangfire.io/en/latest/background-methods/calling-methods-with-delay.html