Search code examples
asp.net-mvcrazorcallbacksmtpclientsendasync

How to display the actual result from SmtpClient.SendAsync() in a asp.net MVC view?


SmtpClient.SendAsync() call will not return a result as SmtpClient.Send() does, but will proceed and cannot display a result in a view. So how do I hook a callback function here, get a send email result/error and display it in a view??

Thanks.


Solution

  • You have two choices:

    a) Call SmtpClient.Send() instead.

    b) Call SmtpClient.SendAsync() it from an asynchronous controller:

    public class HomeController : AsynController
    {
        [HttpPost]
        public void IndexAsync()
        {
            SmtpClient client = new SmtpClient();
    
            client.SendCompleted += (s,e) =>
            {
                AsyncManager.Parameters["exception"] = e.Error;
                AsyncManager.OutstandingOperations.Decrement();
            };
    
            AsyncManager.OutstandingOperations.Increment();
    
            client.Send(GetMessage());
        }
    
        public void IndexCompleted(Exception exception)
        {
            if (exception != null)
            {
                ModelState.AddError("", "Email send failed");
                return View();
            }
            else
            {
                return Redirect("Complete");
            }
        }
    }