I set up a Mailgun route to forward incoming emails to my server endpoint. Everything works fine when emails contain only text content, but as soon as someone sends an email with file attachments, my endpoint receives nothing and the request body comes back empty.
const handleIncomingMail = async (request, response) => {
const senderEmail = request.body.from.split('<')[0].trim();
const originAddress = request.body.sender;
const targetAddress = request.body.recipient;
const emailSubject = request.body.subject;
const content = request.body['stripped-html'];
try {
const newTicket = new HelpDesk({
senderEmail,
originAddress,
targetAddress,
emailSubject,
content
})
await newTicket.save();
response.sendStatus(200)
} catch (err) {
response.status(500)
next(new Error('processing failed'))
}
}
I have URL encoding middleware configured:
app.use(express.urlencoded())
My backend runs on Node.js with Express framework. Any ideas why attachments break the email processing?
yeah, classic mailgun issue. when attachments come thru, it switches to multipart format and breaks your current setup. same thing happened to me last month - spent hours pulling my hair out. express.urlencoded completely ignores multipart content, so you need to add multer middleware before your route handler. that’ll fix it.
Your problem is a content-type mismatch. Mailgun switches from application/x-www-form-urlencoded to multipart/form-data when there are attachments, and express.urlencoded() can’t handle that. I hit this same issue last year building a ticket system. Fix it by adding multipart parsing - I went with busboy instead of multer since it’s lighter for this. You’ll need to bump up your body size limit too since attachments get big. Throw in express.raw() middleware as backup and check the content-type header to handle both cases. Also double-check your Mailgun route settings to make sure it’s sending the right format to your endpoint.
This happens because Mailgun sends multipart form data when there are attachments, but you’re only set up to handle URL-encoded data. Your express.urlencoded() middleware can’t process multipart/form-data - that’s why emails with files break everything. You need multer or another multipart parser. I hit this same issue six months ago and multer fixed it instantly. Once you add it, attachments parse correctly and you can access text fields through request.body again. Without multipart handling, your request body stays empty because Express can’t read the data format.