Send email asynchronously Asp.net mvc

Asked

Viewed 495 times

1

I have a return form Actionresult who sends an email after completing the operation.

I would like to leave this asynchronous email, because it takes a lot of time, I tried to put in a Task using the method Sendmailasync class Smtpclient, yet it doesn’t work.

Someone could tell me what I need to do to send these emails asynchronously on Asp.net mvc?

System.Threading.Tasks.Task.Run(() =>
{
   var smtp = new SmtpClient();
   smtpClient.SendMailAsync(message);
}

3 answers

1


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);
    }
} 
  • I already have a generic class, my problem is that it does not send asynchronously.

  • then put the method of sending email in a generic way in your application too, change it as your need (you will probably need to change the model I created) and call in your controller (or in the correct part of your application) that will work

  • I edited my answer to stay in a more simplified way

0

Try with 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();
}
  • It worked like this Leonardo, is it always delivered correctly? Or can there be losses? Maybe for security I should create a message queue to process the messages?

  • 1

    I use the Task.Factory.StartNew in my projects to do this type of sending email (send and do not wait for confirmation) as the losses, I never had problems, but I do not know if can occur, I believe (I’m not sure) which only fails if you have an exception, you can try to save a log or something like that.

0

you don’t need to create a new Task with the Task.Run or the Task.Factory.StartNew, after all the smtp.SendMailAsync already returns a Task.

All you need to do (or rather not do), is not wait for her return, that is, not to use the await.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.