Question

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.

Was it helpful?

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");
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top