Keeping an Email Conversation in One Slack Thread
Jake MarshIf you post incoming email into Slack and let people answer from the thread, posting the first email is the easy part. The hard part is the second one: when the customer writes back, their reply has to land under the first message, in the same thread, and never as a new message at the top of the channel.
I ran into this building RelayMail, and the fix turned out to be sitting in every email already.
Email Already Solves This#
Every message has a Message-ID. A reply carries In-Reply-To, the message it answers, and References, the chain so far, oldest first. Mail clients build a reply’s References from the parent’s References (or its In-Reply-To if it has none) plus the parent’s Message-ID. So a reply to a reply still names the very first message.
That gives you a stable key. I store each Slack thread against the customer’s first Message-ID, and every later email in the conversation can find it.
Matching an Inbound Email#
When an email arrives, I collect the ids it refers to, most specific first:
In-Reply-ToReferences, read newest to oldest
Then I drop duplicates, skip the email’s own Message-ID, and look each id up until one maps to a thread.
Two small things matter here. Providers send header names in different casing, so I read them case-insensitively. And References can fold across several lines, so I pull ids out with a pattern like <[^<>\s]+> instead of splitting on spaces.
One rule matters more than it looks: a match only counts in the channel the inbox posts to right now. If a stored mapping points at an old channel, or at a different inbox, posting the email there puts it somewhere nobody is watching. In that case I start a new thread instead.
Sending the Reply#
When someone answers in Slack and I send that answer out as an email, I set both headers on it:
In-Reply-To: the customer’s message idReferences: the same id
References is the one that’s easy to skip. Some clients build the next References only from the parent’s References. If mine were empty, the customer’s next email could arrive without the original id anywhere in it, and the thread would break on the third message.
Forwarding Keeps the Headers#
All of this works through a plain forwarding rule. When mail reaches RelayMail through Gmail forwarding, an Outlook rule, a Google Group or an alias, these headers come along unchanged. So I never needed access to anyone’s mailbox to thread correctly. Everything the matching needs travels inside the message itself.
That’s the whole system: one id stored per thread, In-Reply-To then References on the way in, both headers set on the way out, and a match only counts in the inbox’s own channel.