An email to ticket system turns every message sent to your support address into a ticket, and every reply into a comment on that ticket. The pieces are an inbound email provider that receives mail for your domain, a webhook that tells your app about each message, logic that decides “new ticket or reply?”, and outbound email that keeps the customer’s conversation in one thread.
How the flow works
- Receiving.
support@acme.comforwards tosupport@help.acme.com, whose MX points at your inbound provider. Or point the MX directly ifhelp.acme.comis only for tickets. - Webhook. The provider posts the message details to your app.
- Match or create. If the reply address carries a ticket token, or
In-Reply-Tomatches a message you sent, add a comment. Otherwise create a ticket. - Acknowledge. Optionally send one confirmation with the ticket number.
- Agent replies go out by email with thread headers and a Reply-To that comes back to step 2.
Threading: keep one conversation
Email clients thread by headers defined in RFC 5322:
Message-ID: a unique id for each message.In-Reply-To: the id of the message being answered.References: the chain of ids in the conversation.
When an agent replies, set In-Reply-To to the customer’s last Message-ID and append it to References. Keep the subject, prefixed with Re:. Our email headers guide explains each header.
Best practices
- Token in the reply address.
support+t_8f2a@help.acme.com. Random, not the ticket’s database id. - Strip quoted text for the ticket view, but keep the full message available.
- Prevent loops. Ignore inbound mail with
Auto-Submittedother thanno(RFC 3834), and send at most one automatic acknowledgment per sender in a time window. Mark your own acknowledgmentsAuto-Submitted: auto-replied. - Sanitize HTML. Inbound HTML is untrusted. Render it sanitized or as text in the agent view.
- Treat attachments as untrusted. Check type and size; scan if your risk needs it.
- Answer the webhook fast. Return 200, then create the ticket in a background job.
- Ignore duplicates. Webhooks retry; store the inbound email id and skip repeats.
Example: a customer email and an agent reply
From: Sam Buyer <sam@example.com>
To: support@acme.com
Subject: Export stuck at 90%
Message-ID: <CAF123@mail.example.com>
My CSV export has been stuck at 90% since this morning. Project: Q4 plan.
From: Priya at Acme Support <support@acme.com>
Reply-To: support+t_8f2a@help.acme.com
Subject: Re: Export stuck at 90% [#1042]
In-Reply-To: <CAF123@mail.example.com>
References: <CAF123@mail.example.com>
Hi Sam, thanks for the details. We restarted the export and it finished.
You will find the file under Exports. Reply here if it happens again.
Building it with Mailcandor
Inbound email is included on every Mailcandor plan. Point help.acme.com’s MX record at inbound-smtp.us-east-1.amazonaws.com (priority 10), add the domain, and subscribe a webhook to email.received. The webhook has the sender, recipients, subject, message_id and attachment list; the body and headers come from GET /v1/emails/receiving/{id}.
This Flask app verifies the Standard Webhooks signature, then creates a ticket or adds a comment, and has a function to send the agent’s reply:
import base64, hashlib, hmac, os, re, time
import requests
from flask import Flask, request, abort
app = Flask(__name__)
API = "https://api.mailcandor.com/v1"
AUTH = {"Authorization": f"Bearer {os.environ['MAILCANDOR_KEY']}"}
SECRET = base64.b64decode(os.environ["MAILCANDOR_WEBHOOK_SECRET"].removeprefix("mcws_"))
def verified(req) -> bool:
wid, ts = req.headers.get("webhook-id", ""), req.headers.get("webhook-timestamp", "0")
if abs(time.time() - int(ts)) > 300:
return False
signed = f"{wid}.{ts}.".encode() + req.get_data()
expected = base64.b64encode(hmac.new(SECRET, signed, hashlib.sha256).digest()).decode()
return any(hmac.compare_digest(expected, s.removeprefix("v1,"))
for s in req.headers.get("webhook-signature", "").split())
@app.post("/webhooks/mailcandor")
def inbound():
if not verified(request):
abort(401)
event = request.get_json()
if event["type"] == "email.received":
enqueue_ticket_job(event["data"]["email_id"]) # your job queue
return "", 200
def process(email_id: str) -> None:
if already_processed(email_id):
return
email = requests.get(f"{API}/emails/receiving/{email_id}", headers=AUTH, timeout=10).json()
headers = email.get("headers") or {} # keys are lowercase header names
if headers.get("auto-submitted", "no").lower() != "no":
return # never ticket an auto-reply
token = next((m.group(1) for a in email["to"] if (m := re.match(r"support\+(t_\w+)@", a))), None)
ticket = find_ticket(token) if token else None
if ticket:
add_comment(ticket, email)
else:
create_ticket(email)
def send_reply(ticket, body_text: str) -> None:
r = requests.post(f"{API}/emails", headers=AUTH, timeout=10, json={
"from": "Priya at Acme Support <support@acme.com>",
"to": ticket.customer_email,
"reply_to": f"support+{ticket.token}@help.acme.com",
"subject": f"Re: {ticket.subject} [#{ticket.number}]",
"text": body_text,
"headers": {"In-Reply-To": ticket.last_message_id, "References": " ".join(ticket.message_ids)},
"tags": [{"name": "type", "value": "support_reply"}],
})
r.raise_for_status()
Functions like find_ticket and create_ticket are your own. Attachments are listed at GET /v1/emails/receiving/{id}/attachments, each with a download_url valid for one hour. If your endpoint is down, Mailcandor retries the webhook up to 8 times over about 28 hours, and you can replay deliveries or list received mail to catch up.
Should you send an acknowledgment?
An automatic “We got your message, ticket #1042” reassures customers and gives them the ticket number. It is also the email most likely to start a loop. If you send one:
- Send it only for new tickets, not for replies.
- Send at most one per sender address in a set period, such as an hour.
- Never send it to addresses on your own domains or to
noreply-style senders. - Mark it
Auto-Submitted: auto-repliedso other systems know not to answer it. - Tell the customer when to expect a human reply, and keep the promise.
Common pitfalls
- Auto-reply loops. Two systems acknowledging each other can create thousands of tickets overnight.
- Matching on subject only. People change subjects. Use the address token first.
- Rendering raw HTML. An inbound email can carry scripts or tracking pixels into your agents’ browsers.
- Long webhook handlers. Slow responses lead to retries and duplicate tickets.
- Losing the customer’s Message-ID. Without it, replies do not thread in their mail client.