Asynchronous mail blocking MVC requests
The problem code is as follows:
Public class emailhelper
{Private mailhost = NULL; private httpcontext context; public event sendmailcomplete sendcomplete; private smtpclient client;
Public emailhelper () {context = httpcontext. current; client = new smtpclient (); mailhost = new mailhost (); mailhost. host = getazureappsetting ("MailServer"); mailhost. username = getazureappsetting ("mailusername"); mailhost. password = getazureappsetting ("mailpassword ");}
Public void Sendmail (string from, string [] to, string [] CC, string subject, string body ){
Client. Host = mailhost. Host; client. usedefadefacredentials = false; client. Credentials = new networkcredential (mailhost. username, mailhost. Password); client. deliverymethod = smtpdeliverymethod. Network;
Mailmessage message = new mailmessage (); mailaddress mailfrom = new mailaddress (from, getdisplayname (from); encoding mailencoding = encoding. utf8; // encoding. getencoding (DT. rows [0] ["characterset"]. tostring (); message. from = mailfrom;
Foreach (string to in to) {If (! = String. Empty) {message. to. Add ();}}
Foreach (string CC in CC) {If (CC! = String. Empty) {message. CC. Add (CC );}}
Message. Subject = subject; message. Sender = mailfrom; message. Body = body; message. bodyencoding = mailencoding; message. subjectencoding = mailencoding; message. isbodyhtml = true;
// Use new async email as the old one above will block MVC request/Response
Client. sendcompleted + = new sendcompletedeventhandler (sendcompletedcallback); client. sendasync (message, null );}
The solution is as follows:
Public static void internalsendemail (mailmessage mail, smtpclient messages) {internalsendemail (Mail, smtpclient, true);} public static void internalsendemail (mailmessage mail, smtpclient, Boolean async) {If (async) {internalsendemaildelegate ISED = new internalsendemaildelegate (smtpclient. send); asynccallback ACB = new asynccallback (internalsendemailresponse); ISED. begininvoke (Mail, ACB, ISED);} else {smtpclient. send (Mail) ;}} private delegate void internalsendemaildelegate (mailmessage m); Private Static void internalsendemailresponse (iasyncresult AR) {internalsendemaildelegate ISED = (AR. asyncstate); ISED. endinvoke (AR );}
Refer:
Http://weblogs.asp.net/jeffwids/archive/2009/10/12/asynchronously-sending-a-system-net-mail-mailmessage-in-c.aspx? Commentposted = true # commentmessage
Https://connect.microsoft.com/VisualStudio/feedback/details/688210/smtpclient-sendasync-blocking-my-asp-net-mvc-request#details