Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop for resending smtp email on failure to send

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.
        }
    }
like image 211
Rex_C Avatar asked Jun 18 '14 18:06

Rex_C


1 Answers

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)
}
like image 60
TheNorthWes Avatar answered Nov 04 '22 12:11

TheNorthWes