I need help creating a C# MVC action method that can process incoming emails sent by Mailgun webhooks. I found some Python sample code in their docs but I’m not sure how to translate it to C#. Here’s what the Python version looks like:
def incoming_email(request):
if request.method == 'POST':
sender = request.POST.get('sender')
recipient = request.POST.get('recipient')
subject = request.POST.get('subject', '')
body_plain = request.POST.get('body-plain', '')
body_without_quotes = request.POST.get('stripped-text', '')
for key in request.FILES:
file = request.FILES[key]
# Handle the file here
return HttpResponse('OK')
What’s the proper way to set this up in ASP.NET MVC? Do I need any special routing or configuration? Any help would be great!
The C# version is pretty straightforward. Create an action method that handles POST requests and pulls webhook data from the Request object. Here’s what I used in my project:
[HttpPost]
public ActionResult IncomingEmail()
{
string sender = Request.Form["sender"];
string recipient = Request.Form["recipient"];
string subject = Request.Form["subject"] ?? string.Empty;
string bodyPlain = Request.Form["body-plain"] ?? string.Empty;
string strippedText = Request.Form["stripped-text"] ?? string.Empty;
// Handle file attachments
foreach (string key in Request.Files)
{
HttpPostedFileBase file = Request.Files[key];
if (file != null && file.ContentLength > 0)
{
// Process your attachment here
}
}
return new HttpStatusCodeResult(200, "OK");
}
No special routing required - just point your Mailgun webhook URL to this action. Main difference from Python is you use Request.Form instead of request.POST.
I hit the same issue last year with Mailgun webhooks. The big gotcha was webhook verification - Mailgun sends a signature with each request that you need to validate. Otherwise, anyone can spam your endpoint. Use the timestamp, token, and signature fields they send to verify it’s actually from them. Request.Form works for basic stuff, but if you’re handling lots of emails or complex processing, just create a model class that maps to their webhook params. Way cleaner code and easier to maintain. Two other things: disable CSRF validation for that action since external webhooks can’t send anti-forgery tokens. And double-check your webhook URL in the Mailgun dashboard matches exactly - including area prefixes if you’re using them. Default MVC routing should work fine otherwise.
make sure your controller accepts POST requests and watch for content-type issues. Mailgun sends multipart/form-data, so default model binding often breaks. I grab everything with Request.Form like the first answer shows, but I also check Request.Headers when debugging goes sideways.