How to Handle POST Data from Mailgun in Rails Application

I’m struggling with processing POST parameters sent by Mailgun to my Rails app. I need to capture email data and save it to my database, but something isn’t working correctly.

Here’s my routing setup:

post '/webhooks/email', to: 'email_handler#process'

And here’s my controller code:

class EmailHandlerController < ApplicationController
  
  skip_before_action :verify_authenticity_token, only: [:process]
  
  def show
  end
  
  def process
    Rails.logger.info "Email webhook data: #{params}"
    
    email_subject = EmailData.new(params[:Subject])
    email_subject.save
    
    sender_info = EmailData.new(params[:sender])
    sender_info.save
    
    message_content = EmailData.new(params['stripped-text'])
    message_content.save
    
    render json: { status: 'ok' }, status: 200
  end
end

I can see the webhook requests coming through in my server logs, but the data isn’t getting saved to the database. I also want to test this setup on my local development environment. What could be going wrong here?

Your EmailData model initialization is the problem. You’re passing raw parameter values straight to EmailData.new(), but Rails models need attribute hashes. Check your schema and fix it - try EmailData.create(subject: params['Subject'], sender: params['sender']) instead. Make sure your migrations ran and the EmailData table exists with the right columns. I had the same issue where saves failed silently because my table structure didn’t match what I was saving. Add error checking with unless email_subject.save and log the validation errors to see what’s actually breaking.

You’re mixing symbol and string keys when accessing params, which won’t work with Mailgun webhooks. Mailgun sends data with specific key names, so stick to one format consistently. I hit this same issue when I first set up Mailgun integration. Your EmailData model creation is also broken - you’re passing single values instead of attribute hashes. Try EmailData.create(content: params['Subject']) instead. For local testing, use ngrok to expose your dev server. Run ngrok http 3000 and drop that URL into your Mailgun webhook config. And definitely add error handling around your save operations - validation failures might be silently killing your database writes.

you’re probably missin some required attributes in ur EmailData model. log params.inspect to see exactly what Mailgun’s sending. also check if ur model validations are blockin the save - might be a simple fix!