循环以在发送失败时重新发送smtp电子邮件

时间:2014-06-18 18:23:23

标签: c# email smtpclient

我有一项服务,在用户注册后发送电子邮件。每隔一段时间,用户会联系支持他们没有收到电子邮件的投诉,所以我列出了可能出现的问题,其中一个是smtp无法发送电子邮件,我偶尔会注意到将逐步完成代码。我想写一个简单的循环,尝试重新发送电子邮件几次失败发送,但我不知道如何去做。我很感激有关这个问题的任何建议。

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.
        }
    }

2 个答案:

答案 0 :(得分:7)

这样的事情可以解决问题:

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)
}

答案 1 :(得分:3)

你可以反复做到

首先定义最大重试次数

public const int MAX_RETRY_COUNT = 3;

然后使用重试计数

调用该方法
MusicDownloadEmail("code@mail.com", MAX_RETRY_COUNT);

并修改方法如下

public static void MusicDownloadEmail(string email, int retryCountsLeft) {
        if (retryCountsLeft > 1) {
            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.

                MusicDownloadEmail(email, --retryCountsLeft);
            }
        }
    }