Reputation: 1566
I recently end up having a problem with the limite of 30 mails per minute from office 365, I'm making this question to look for other solutions and also show the solution I did to overcome the 30 mails per minute limit.
Upvotes: 0
Views: 177
Reputation: 1566
for the 30 mails per minute problem you can solve it just by creatring a Queued background service: enter link description here
Then you can just create a class EmailQueuedHostedService that inherits from QueuedHostedService and override the BackgroundProcessing method like this:
public class EmailQueuedHostedService : QueuedHostedService
{
private readonly ILogger<EmailQueuedHostedService> _logger;
private readonly TimersTimer _timer;
private int MailsSent = 0;
private const int MailsSentInMinute = 30;
public EmailQueuedHostedService(IBackgroundTaskQueue taskQueue,
ILogger<EmailQueuedHostedService> logger) : base(taskQueue, logger)
{
_logger = logger;
_timer = new TimersTimer(60 * 1000);
_timer.Elapsed += (sender, e) => MailsSent = 0;
_timer.Start();
}
protected override async Task BackgroundProcessing(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
if (MailsSent < MailsSentInMinute)
{
var workItem = await TaskQueue
.DequeueAsync(stoppingToken);
try
{
await workItem(stoppingToken);
MailsSent++;
}
catch (Exception ex)
{
_logger.LogError(ex,
"Error occurred executing {WorkItem}.", nameof(workItem));
}
}
}
}
}
Now your Email Queue service will control the number of emails send per minute so they don't throw an exception if you pass the limit.
Upvotes: 1