Architecture
Turning a support mailbox into a ticket system
Pulling a shared inbox into the admin panel with IMAP so support requests from the contact form and from email land in one queue. The UID bookkeeping that makes it incremental, and the two bugs I found writing this up.
Support requests arrived through two doors. Some came through the contact form on the website and landed in a database table. The rest came to a support email address and sat in a shared mailbox that somebody had to remember to open.
Two queues means two habits, and the one nobody is looking at is where things get missed. The customer does not know or care which door they used; they just know nobody replied. Buying a helpdesk product was disproportionate for the volume, so the mailbox came into the admin panel instead.
Sync incrementally, using UIDs
The naive version fetches the whole mailbox every time and reconciles. That works for a week and then the sync takes a minute and downloads several thousand messages to find the two that are new.
IMAP gives you the tool to avoid that. Every message in a mailbox has a UID, and UIDs are assigned in ascending order and never reused. So you record the highest one you have seen and ask only for what came after it:
const [stateRows] = await db.query(
'SELECT last_uid FROM support_mailbox_state ORDER BY id DESC LIMIT 1'
)
const lastUid = stateRows.length ? Number(stateRows[0].last_uid || 0) : 0
const range = lastUid > 0 ? `${lastUid + 1}:*` : '1:*'
for await (const message of client.fetch(range, {
uid: true, envelope: true, source: true, internalDate: true
})) { /* ... */ }One thing to know about that range syntax: `n:*` always returns at least one message, because if no message has a UID at or above n, the server returns the last one in the mailbox. So the fetch is never empty even when nothing is new, and the insert has to be idempotent regardless.
Which it is, because the UID is a unique key and the insert upserts on it:
INSERT INTO support_emails
(uid, message_id, from_email, from_name, subject, body_text, body_html, received_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
message_id = VALUES(message_id),
from_email = VALUES(from_email),
/* ... */
received_at = VALUES(received_at)That combination, a bookmark plus an idempotent write, means the bookmark does not have to be perfectly accurate. A sync that crashes halfway leaves the bookmark behind where it should be, the next run re-fetches a few messages, and they land on the rows that already exist. Exactly-once processing is hard; at-least-once processing with idempotent writes is easy and usually equivalent.
The bookmark is only advanced after the loop completes, which is the right order. Advancing it as you go would mean a crash mid-loop skips whatever was fetched but not yet stored.
The UIDVALIDITY trap
Here is the part of IMAP that catches everyone, and this implementation has it.
UIDs are only unique and monotonic within a given incarnation of a mailbox. Every mailbox also carries a UIDVALIDITY value, and the protocol's contract is: if UIDVALIDITY changes, every UID you have stored is meaningless. That happens when a mailbox is deleted and recreated, when some server-side migration renumbers things, or when a provider moves your account between systems.
The failure is quiet and asymmetric. If the new numbering starts lower than your stored bookmark, you request a range above everything that exists and sync nothing, forever, with no error. Support emails stop appearing in the panel and the sync reports success every time.
const lock = await client.getMailboxLock('INBOX')
const { uidValidity } = client.mailbox
// Stored alongside last_uid: if it has changed, the bookmark is void.
if (storedUidValidity && String(uidValidity) !== String(storedUidValidity)) {
lastUid = 0 // resync from the beginning; the upsert makes that safe
}It is a few lines and it is the difference between a sync that recovers on its own and one that silently stops. The upsert is what makes a full resync a safe response rather than a duplicate-generating one.
Any time you store an external system's identifier as a bookmark, ask what invalidates it. IMAP tells you explicitly with UIDVALIDITY, which is more than most systems do, and it is still easy to ignore.
Parse defensively, from two sources
Email is not a clean format. Encodings vary, headers are optional in practice regardless of what the specification says, and the display name may or may not exist. The fetch asks for both the parsed envelope and the raw source, and the code prefers the fully parsed version while falling back to the envelope:
const parsed = message.source ? await simpleParser(message.source) : null
const envelope = message.envelope || {}
const fromValue = parsed?.from?.value?.[0] || envelope.from?.[0]
const subject = parsed?.subject || envelope.subject || null
const receivedAt = message.internalDate || envelope.date || nullNote that received time prefers internalDate, which is when the server received the message, over the Date header, which is whatever the sender's machine claimed. Sender clocks are wrong often enough that sorting a support queue by the Date header produces messages from the future.
Both the text and HTML bodies are stored. Storing only one means either losing formatting or being unable to display a plain text message from a client that sent no HTML.
Release the lock, close the connection
IMAP is a stateful, connection-oriented protocol, and providers cap concurrent connections at numbers lower than you expect. Leak connections and the sync starts failing with an authentication error that has nothing to do with authentication.
} finally {
try { if (lock) lock.release() } catch (error) {
console.error('Error releasing IMAP lock:', error)
}
try { await client.logout() } catch (error) {
console.error('Error closing IMAP connection:', error)
}
}Two separate try blocks inside the finally, so a failure to release the lock still lets the logout run. A single try around both would let the first failure skip the second, which is exactly the case where you most need the connection closed.
One reply endpoint, two sources
The point of the exercise is replying without leaving the panel. Both message types go through one route, distinguished by a source type:
router.post('/support/reply', adminAuth, checkPermission('support', 'reply'), async (req, res) => {
const { sourceType, sourceId, subject, body } = req.body
let target = null
if (sourceType === 'contact') {
const [rows] = await db.query('SELECT * FROM contact_messages WHERE id = ?', [sourceId])
target = rows[0]
} else if (sourceType === 'inbox') {
const [rows] = await db.query('SELECT * FROM support_emails WHERE id = ?', [sourceId])
target = rows[0]
} else {
return res.status(400).json({ message: 'Invalid sourceType' })
}
// ...send, record, update status
})The recipient address is resolved from the target record rather than accepted from the request, which is the important detail. Taking a to address from the client would turn an authenticated support tool into an open relay wearing your domain's reputation.
Every reply is recorded with the SMTP message id and the admin who sent it, and the source record's status moves to replied with a timestamp. That gives the queue an unanswered filter, which is the only thing that makes it a queue rather than a list.
The threading bug
This one I found while writing this article, and it is the most useful thing here because the code looks complete.
const finalSubject = subject || `Re: ${target.subject || 'Support Request'}`
await transporter.sendMail({
from: `"Sell Prime Support" <${process.env.SMTP_USER}>`,
to: toEmail,
subject: finalSubject,
text: body,
html: `<p style="white-space: pre-line;">${body}</p>`,
})The reply prefixes Re: and sends. What it does not do is set In-Reply-To or References, and those headers are what mail clients actually use to thread a conversation. Subject matching is a fallback heuristic that Gmail leans on and many clients do not.
So the customer receives a reply that appears as a new, unrelated message rather than as part of the conversation they started. They have lost the context of their own question, and if they reply to it, the threading is broken in both directions.
The fix uses the message id that is already being stored during the sync and currently used for nothing:
await transporter.sendMail({
// ...
inReplyTo: target.message_id ?? undefined,
references: target.message_id ?? undefined,
})That is a satisfying kind of bug: the hard part, capturing and persisting the identifier, was already done. Only the last hop was missing.
And an unescaped interpolation
Look again at the HTML body:
html: `<p style="white-space: pre-line;">${body}</p>`The reply text goes straight into HTML with no escaping. The severity is low, because the author is an authenticated admin with a reply permission rather than a member of the public. The everyday consequence is not.
An admin writing a perfectly ordinary sentence containing a less-than sign produces an email where everything after it disappears into what the renderer treats as a tag. Angle brackets show up in support replies more than you would think, in prices, comparisons and pasted error messages. Escape the five HTML entities before interpolation, or build the body with a template library that escapes by default.
What to take from this
- Fetch by UID range from a stored bookmark, and advance the bookmark only after the batch succeeds.
- Make the write idempotent on the UID, so an interrupted sync is safe to repeat.
- Store UIDVALIDITY beside the bookmark and resync from zero when it changes, or your sync stops silently.
- Remember that n:* returns at least one message even when nothing is new.
- Parse from the full source with the envelope as a fallback, and prefer the server's internal date over the sender's clock.
- Store both text and HTML bodies.
- Release the mailbox lock and log out in a finally, in separate try blocks.
- Resolve the recipient from the stored record, never from the request.
- Set In-Reply-To and References. A Re: prefix is not threading.
- Escape anything you interpolate into HTML, even when the author is trusted.
The feature is worth the effort for a reason that is not technical: one queue creates one habit. Two queues means one of them is checked less often, and the customers in it are the ones who quietly stop being customers. The admin panel this lives in, including the permission model gating that reply route, is described in the SellPrime case study.