I have a fairly weird issue that I can't wrap my head around. So here is the code:
[HttpGet]
[AllowAnonymous]
public ActionResult SendEmail()
{
SendRegisterEmail("Test", "Testagain", "lastTest");
return View("Index");
}
public async Task<bool> SendRegisterEmail(string subject, string message, string to)
{
var email = new Email();
var mailAddress = new MailAddress(to);
email.Subject = subject;
email.Body = message;
var mailAddressCollection = new MailAddressCollection();
mailAddressCollection.Add(mailAddress);
email.To = (mailAddressCollection);
return await Send(email);
}
Now to prove my problem I broke down the code into single lines so I can see on which line it breaks. Here is what I found:
When I debug this and I step into the SendRegisterEmail
method, the line that says var mailAddress = new MailAddress(to);
gets run and then it exits out the function and runs the line return View("Index");
and the page loads up. The weird thing is I added a logging method on to Send at the very end and that logging never gets hit. I put a breakpoint on Send and it never got hit. It is as if creation of email crashed, decided to exit out to the caller function and continued with the code.
I don't have a faintest clue as to why.
SendRegisterEmail
method is asynchronous, you're not awaiting for it.Currently, you start a fire-and-forget operation and
return View
instruction is executed while you're creating a newMailAddress
instance. Most probably it throwsFormatException
which you can't catch because the exception is thrown in another thread.update your action method to
Also awaiting before the return is not really needed, you can change it to
but that's not related to the problem you've got.