Send email asynchronously asp.net mvc

1

I have a form that returns ActionResult that sends an email after completing the operation.

I would like to leave this email asynchronous, because it takes a lot of the time, I tried to put it in a Task using the SendMailAsync method of the SmtpClient class >, however it does not work.

Can anyone tell me what I need to do to send these emails asynchronously in asp.net mvc?

System.Threading.Tasks.Task.Run(() =>
{
   var smtp = new SmtpClient();
   smtpClient.SendMailAsync(message);
}
    
asked by anonymous 04.09.2017 / 23:51

3 answers

0

Edit:

Just follow the example:

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);
    }
} 
    
05.09.2017 / 13:45
0

Try the following code:

public async Task<ActionResult> MyAcation()
{
    //Codigo de criacao do objeto message
    Task.Factory.StartNew(() =>
    {
       var smtp = new SmtpClient();
       smtp.SendMailAsync(message);
    });
    return View();
}
    
05.09.2017 / 01:17
0

You do not need to create a new Task with Task.Run or Task.Factory.StartNew , after all smtp.SendMailAsync already returns a Task .

All you have to do (or not do) is do not wait for it to return, ie do not use await .

public async Task<ActionResult> MyAcation()
{
    var smtp = new SmtpClient();
    smtp.SendMailAsync(message);
    return View();
}
    
05.09.2017 / 17:08