Xiolin
Xiolin

Reputation: 131

Respond to MailGun's HTTP post and then process the message

When receiving mail through MailGun they require a response within a limited time. I have two issues with this:

1) After receiving the message I need to process and record it in my CRM which takes some time. This causes MailGun to time out before I get to send a response. Then MailGun resends the message again and again as it continues to time out.

2) MailGun's post is not async but the api calls to my CRM are async.

So I need to send MailGun a 200 response and then continue to process the message. And that process needs to be in async.

The below code shows what I want to have happen. I tried using tasks and couldn't get it working. There are times when many emails can come in a once (like when initializing someone's account) if the solution requires some sort of parallel tasks or threads it would need to handle many of them.

    public class HomeController : Controller
    {
        [HttpPost]
        [Route("mail1")]
        public ActionResult Mail()
        {
            var emailObj = MailGun.Receive(Request);

            return Content("ok");

            _ = await CRM.SendToEmailApp(emailObj);
        }
    }

Thank you for the help!

Upvotes: 0

Views: 274

Answers (1)

Ashkan Nourzadeh
Ashkan Nourzadeh

Reputation: 1942

The easiest way to do what you are describing (which is not recommended, because you may lose some results if your app crash) is to use a fire & forget task:

var emailObj = MailGun.Receive(Request);
Task.Run(async () => await CRM.SendToEmailApp(emailObj));
return Content("ok");

But, I think what you really want is sort of a Message Queue, by using a message queue you put the message in the queue (which is fast enough) and return immediately, at the same time a processor is processing the message queue and saves the result in the CRM.
This is what it'll look like when you use a message queueing broker.

simple architecture

Upvotes: 1

Related Questions