ASP.NET C# implementation for handling Mailgun webhook POST requests

I’m attempting to create a webhook in my ASP.NET application to manage incoming emails from Mailgun. I need to work with the data that Mailgun sends via POST when an email is received.

Here’s the approach I am taking in my controller:

public ActionResult ProcessEmail()
{
    if (Request.HttpMethod == "POST")
    {
        string fromAddress = Request.Form["from"];
        string toAddress = Request.Form["to"];
        string emailSubject = Request.Form["subject"] ?? "";
        
        string plainText = Request.Form["body-plain"] ?? "";
        string cleanedText = Request.Form["stripped-text"] ?? "";
        
        // Handle file uploads
        foreach (string fileKey in Request.Files.AllKeys)
        {
            HttpPostedFileBase uploadedFile = Request.Files[fileKey];
            // Process the uploaded file
        }
        
        return new HttpStatusCodeResult(200, "Success");
    }
    
    return new HttpStatusCodeResult(405, "Method Not Allowed");
}

However, I’m receiving a 500 error from Mailgun when I test this setup. The webhook isn’t functioning correctly, and I am unsure what I am missing. Has anyone else successfully set up a Mailgun webhook using ASP.NET?

Your controller method looks mostly right, but a few things are causing that 500 error. Make sure your action handles multipart/form-data since that’s how Mailgun sends webhooks. Wrap your form field access in try-catch blocks - some fields won’t exist depending on the email content. I hit this exact issue last year when Request.Form threw exceptions for missing fields. Also check that your webhook URL is publicly accessible and returns 200 within Mailgun’s timeout. Test with a simple response first, then add the email processing once the basic webhook works.

That 500 error is usually authentication issues or bad request handling. Mailgun signs their requests and you need to verify them properly.

Honest? Skip the ASP.NET webhook headaches and automate this whole thing. I hit the same wall with email processing and ended up building a solution that handles Mailgun webhooks automatically.

No controller code, no request parsing nightmares. The automation platform catches the webhook, validates it, grabs all the email data (attachments included), then routes it wherever you want - database, APIs, file storage, you name it.

Turns hours of debugging into minutes of setup. Plus you get error handling and retry logic that ASP.NET makes you build yourself.

Check it out: https://latenode.com

check if ur webhook endpoint allows anonymous access - auth can block mailgun requests. also make sure the webhook URL in ur mailgun dashboard matches exactly what u deployed, including http vs https.

add [HttpPost] above your method, it helps. also check the response content type. mailgun can be picky with formats, had similar issues b4.