I have a service that sends an email after a user registers. Every once in a while, a user contacts support with the complaint that they aren't receiving the email, so I've made a list of possible issues, one of which is a smtp failure to send email, which I noticed occasionally when I would step through the code. I want to write a simple loop that tries to resend the email a couple of times on failure to send, but I'm not sure how to go about doing that. I'd appreciate any advice on the subject.
public void MusicDownloadEmail(string email)
{
try
{
var smtp = new SmtpClient();
var mail = new MailMessage();
const string mailBody = "Body text";
mail.To.Add(email);
mail.Subject = "Mail subject";
mail.Body = mailBody;
mail.IsBodyHtml = true;
smtp.Send(mail);
}
catch (Exception ex)
{
var exception = ex.Message.ToString();
//Other code for saving exception message to a log.
}
}
Something like this should do the trick:
public void MusicDownloadEmail(string email)
{
int tryAgain = 10;
bool failed = false;
do
{
try
{
failed = false;
var smtp = new SmtpClient();
var mail = new MailMessage();
const string mailBody = "Body text";
mail.To.Add(email);
mail.Subject = "Mail subject";
mail.Body = mailBody;
mail.IsBodyHtml = true;
smtp.Send(mail);
}
catch (Exception ex) // I would avoid catching all exceptions equally, but ymmv
{
failed = true;
tryAgain--;
var exception = ex.Message.ToString();
//Other code for saving exception message to a log.
}
}while(failed && tryAgain !=0)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With