need code for ASP .NET C# to try and resend email failed to send via smtpclient

William Dias 1 Reputation point
2021-10-26T13:56:07.193+00:00

need code which can try and resend emails which are sent via C# ASP .NET application for those email which receive error on first attempt.

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,597 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Lan Huang-MSFT 30,186 Reputation points Microsoft External Staff
    2021-10-27T09:58:17.85+00:00

    Hi @William Dias ,
    I suggest you can use try-catch to handle exceptions. You can include codes that may cause an exception in a try block. If you send email failed ,it could for loop to send the email.
    You can refer to the following code:

    public void DownloadEmail(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)  
            {                  
                failed = true;  
                tryAgain--;  
                var exception = ex.Message.ToString();  
                //Other code for saving exception message to a log.  
            }  
        }  
       while(failed  && tryAgain !=0)  
    }  
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.