Proper way to asynchronously send an email in ASP.NET… (am i doing it right?)

前端 未结 9 1611
时光取名叫无心
时光取名叫无心 2020-12-23 10:57

When a user registers on my website, I don\'t see why I need to make him \"wait\" for the smtp to go through so that he gets an activation email.

I decided I want to

相关标签:
9条回答
  • 2020-12-23 11:01

    If you want to detect leaks, then you need to use a profiler like this one:

    http://memprofiler.com/

    I don't see anything wrong with your solution, but can almost guarantee you that this question will be closed as subjective.

    One other option is to use jQuery to make an ajax call to the server and spark the e-mail flow. That way, the UI is not locked up.

    Good luck!

    Matt

    0 讨论(0)
  • 2020-12-23 11:02

    There was a lot of good advice that I upvoted here... such as making sure to remember to use IDisposable (i totally didn't know). I also realized how important it is to manually catch errors when in another thread since there is no context -- I have been working on a theory that I should just let ELMAH handle everything. Also, further exploration made me realize I was forgetting to use IDisposable on mailmessage, too.

    In response to Richard, although I see that the threading solution can work (as suggested in my first example) as long as i'm catching the errors... there's still something scary about the fact that IIS completely explodes if that error isn't caught. That tells me that ASP.NET/IIS never meant for you to do that... which is why i'm leaning towards continuing to use .BeginInvoke/delegates instead since that doesn't mess up IIS when something goes wrong and seems to be more popular in ASP.NET.

    In response to ASawyer, I was totally surprised that there was a .SendAsync built into the SMTP client. I played with that solution for a while, but it doesn't seem to do the trick for me. Although I can skip through the client of code that does SendAsync, the page still "waits" until the SendCompleted event is done. My goal was to have the user and the page move forward while the email is getting sent in the background. I have a feeling that I might still be doing something wrong... so if someone comes by this they might want to try it themselves.

    Here's my full solution for how I sent emails 100% asynchronously in addition with ELMAH.MVC error logging. I decided to go with an expanded version of example 2:

    public void SendThat(MailMessage message)
    {
        AsyncMethodCaller caller = new AsyncMethodCaller(SendMailInSeperateThread);
        AsyncCallback callbackHandler = new AsyncCallback(AsyncCallback);
        caller.BeginInvoke(message, callbackHandler, null);
    }
    
    private delegate void AsyncMethodCaller(MailMessage message);
    
    private void SendMailInSeperateThread(MailMessage message)
    {
        try
        {
            SmtpClient client = new SmtpClient();
            client.Timeout = 20000; // 20 second timeout... why more?
            client.Send(message);
            client.Dispose();
            message.Dispose();
    
            // If you have a flag checking to see if an email was sent, set it here
            // Pass more parameters in the delegate if you need to...
        }
        catch (Exception e)
        {
             // This is very necessary to catch errors since we are in
             // a different context & thread
             Elmah.ErrorLog.GetDefault(null).Log(new Error(e));
        }
    }
    
    private void AsyncCallback(IAsyncResult ar)
    {
        try
        {
            AsyncResult result = (AsyncResult)ar;
            AsyncMethodCaller caller = (AsyncMethodCaller)result.AsyncDelegate;
            caller.EndInvoke(ar);
        }
        catch (Exception e)
        {
            Elmah.ErrorLog.GetDefault(null).Log(new Error(e));
            Elmah.ErrorLog.GetDefault(null).Log(new Error(new Exception("Emailer - This hacky asynccallback thing is puking, serves you right.")));
        }
    }
    
    0 讨论(0)
  • 2020-12-23 11:05

    Threading isn't the wrong option here, but if you don't handle an exception yourself, it will bubble up and crash your process. It doesn't matter which thread you do that on.

    So instead of mailer.SendTheMail() try this:

    new Thread(() => { 
      try 
      {
        mailer.SendTheMail();
      }
      catch(Exception ex)
      {
        // Do something with the exception
      }
    });
    

    Better yet, use the asynchronous capabilities of the SmtpClient if you can. You'll still need to handle exceptions though.

    I would even suggest you have a look at .Net 4's new Parallet Task library. That has extra functionality which lets you handle exceptional cases and works well with ASP.Net's thread pool.

    0 讨论(0)
  • 2020-12-23 11:06

    Are you using the .Net SmtpClient to send email? It can send asynch messages already.

    Edit - If Emailer mailer = new Emailer(); is not a wrapper over SmtpClient, this won't be so useful I imagine.

    0 讨论(0)
  • As of .NET 4.5 SmtpClient implements async awaitable method SendMailAsync. As a result, to send email asynchronously is as the following:

    public async Task SendEmail(string toEmailAddress, string emailSubject, string emailMessage)
    {
        var message = new MailMessage();
        message.To.Add(toEmailAddress);
    
        message.Subject = emailSubject;
        message.Body = emailMessage;
    
        using (var smtpClient = new SmtpClient())
        {
            await smtpClient.SendMailAsync(message);
        }
    } 
    
    0 讨论(0)
  • 2020-12-23 11:13

    I worked same issue for my project:

    First tried Thread as you do:
    - I loose context
    - Exception handling problem
    - Commonly said, Thread are bad idea on IIS ThreadPool

    So I switch and try with asynchronously:
    - 'asynchronously' is fake in a asp.net web application. It just put queue calls and swicth the context

    So I make windows service and retrive the values through sql table: happy end

    So for quick solution: from ajax side make async call tell the user fake yes, but continue your sending job in your mvc controller

    0 讨论(0)
提交回复
热议问题