Reputation: 410
I'm trying to send an email using Postal MVC in my MVC controller. I want to send the email asynchronously and don't want to wait for the email to be sent before I return the View.
Here is the code that I'm trying to use.
try
{
dynamic email = new Email("TestEmail"); //I have an Email View by this name
email.To = "[email protected]";
email.From = "[email protected]";
email.SendAsync(); //email.Send() works fine
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
But I get this error "Failure sending mail."
Inner Exception System.InvalidOperationException:An asynchronous operation cannot be started at this time.Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle.If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %>. at System.Web.AspNetSynchronizationContext.OperationStarted() at System.ComponentModel.AsyncOperation.CreateOperation(Object userSuppliedState,SynchronizationContext syncContext) at System.Net.Mail.SmtpClient.SendAsync(MailMessage message,Object userToken)
If I replace the SendAsync() with Send() it works fine.
For completeness sake, this what my mailSettings look like in my Web.Config
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network host="smtp.myisp.com" port="25" defaultCredentials="true" />
</smtp>
</mailSettings>
</system.net>
Something seems to be wrong with sending the email asynchronously. Has anyone else come up with this problem and have a solution?
Or should I use another mailer like MvcMailer?
Please don't suggest that I should not send the email asynchronously. I want the response of my site to be fast and I find connecting to an email server to send an email during a sign up process to be a little non-responsive.
Upvotes: 0
Views: 4041
Reputation: 2550
It would appear that Postal MVC is not compatible with MVC4's new Async mechanism. Until the developers of Postal MVC make it compatible you have 2 options, downgrade to MVC3, or force the old MVC3 functionality in your application.
To revert to the old functionality in MVC4, you can apply the following setting in your web.config:
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" />
Be wary of just doing this though, there may be implications within your site from doing this. I suggest that you research the implications.
Upvotes: 2
Reputation: 20674
Make sure you have the latest version of Postal. They have included a unit test of sending Async which should help you understand what's wrong. This suggests it is not a problem with Postal.
The test also suggests that you might have to use a SpecifiedPickupDirectory
Upvotes: 0