Send mail with smtp SendAsync

后端 未结 3 616
滥情空心
滥情空心 2021-01-24 22:58

this is how when I need to send email gives me error. But the mistake that since gives me is this:

An asynchronous operation cannot be started at this tim

相关标签:
3条回答
  • 2021-01-24 23:36

    Not really replying your original question, but just wanted to stress that you are better off calling an email sending code without keeping the calling thread waiting. Although you are using async/await, in user's perspective, you are still waiting in the browser while the server is done sending emails. It may be few milliseconds, but still it's better to let this handled by a background worker.

    So IMO, using HostingEnvironment.QueueBackgroundWorkItem(x=> SendEmail()); would be a better approach.

    Having said that, you still have a slight risk of the asynchronous task being terminated if app domain recycles in the middle. But that's highly unlikely in your case I would say. Even if that happens, you can use a cancellation token and work your way around it.

    0 讨论(0)
  • 2021-01-24 23:39

    Change your method to:

    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);
    }
    }
    

    And call it like:

    var task = SendEmail(toEmailAddress, emailSubject, emailMessage);
    var result = task.WaitAndUnwrapException();
    

    Have a look here Asynchronously sending Emails in C#? and here How to call asynchronous method from synchronous method in C#?

    0 讨论(0)
  • 2021-01-24 23:45

    You can also try to define your async option inside a separate thread. I believe that you already have inserted the async tag in your page. And if everything is okay then try to put your code in below block.

     this.Page.RegisterAsyncTask(new PageAsyncTask(async ctoken => {
          var result = await SomeOperationAsync(ctoken);
          // result operations.
    }));
    
    0 讨论(0)
提交回复
热议问题