The following would be executed with a while statement which should have logic to exit after x attempts or use a for/next e.g. after say 5 attempts abort.
using System;
using System.ComponentModel;
using System.Net.Mail;
using System.Threading.Tasks;
namespace EmailLibrary
{
public class Operations
{
public delegate void OnSendCompleted(object sender, AsyncCompletedEventArgs eventArguments);
public static event OnSendCompleted SendCompleted;
public static async Task<(bool success, Exception exception)> SendEmail(MailMessage message)
{
try
{
var smtp = new SmtpClient();
smtp.SendCompleted += OnCompleted;
await smtp.SendMailAsync(message);
return (true, null);
}
catch (Exception e)
{
return (false, e);
}
}
private static void OnCompleted(object sender, AsyncCompletedEventArgs eventArguments)
{
SendCompleted?.Invoke(sender, eventArguments);
}
}
}
Calling, needs message setup
public async Task Send()
{
for (int index = 0; index < 5; index++)
{
var (success, exception) = await Operations.SendEmail(new MailMessage());
if (success)
{
return;
}
else
{
// log exception and pause
await Task.Delay(500);
}
}
}