Skip to main content

Mailgun Module

Send emails and newsletters from a workflow through your own Mailgun domain, with Mailgun's API: one email, or a personal copy for every row of a list (thousands a day), with one-click unsubscribe. Mailgun's events (delivered, failed, unsubscribed, marked as spam, opened, clicked) can start a process, so bounces and opt-outs flow back into your CRM.

The Mailgun Module adds four Tasks:

  • MailgunSendBatch sends one personal copy of an email to every row of a list, up to 1,000 recipients per Mailgun call.
  • MailgunSendEmail sends one email.
  • MailgunSuppression adds an address to, removes it from, or checks it on the domain's unsubscribes, bounces or complaints.
  • MailgunStart starts the process when Mailgun reports an event of the domain.

The emails are built like the Email and MailKit Modules build them: from one of your Workspace's email templates (Storage → Templates), from HTML written in the Task, or from plain text, with {variable} placeholders filled when the email is sent.

What you can build​

  • A newsletter to every contact who opted in: Query records reads the contacts, Send batch sends the newsletter template to all of them with {row.firstName} filled per contact, and Mailgun adds the one-click unsubscribe headers Gmail and Yahoo require (MailgunSendBatch).
  • Opt-outs back in the CRM: a Mailgun start ticked for Unsubscribed and Marked as spam updates the contact {mailgun.userVariables.contactId} that the send put in a custom variable (MailgunStart, then Update record).
  • Bounce cleanup: a Mailgun start ticked for Failed marks {mailgun.recipient} as undeliverable when {mailgun.severity} is permanent.
  • Your own opt-outs pushed to Mailgun: when a contact unsubscribes on your site, MailgunSuppression adds them to the domain's unsubscribes, so no later send reaches them.
  • Order confirmations from your marketing domain with tags and tracking (MailgunSendEmail).
  • A delivery report after a campaign: a Switch on {result.failed} emails the rows that could not be sent to the team.

Quick start​

  1. In Mailgun, add and verify your sending domain (for example news.example.com) in Sending → Domains, with its SPF, DKIM and tracking (CNAME) records.
  2. In Mailgun API Security, create an API key, and copy the HTTP webhook signing key.
  3. In the portal, open the Environment's Mailgun settings: paste the API key and the webhook signing key, pick the Region (EU or US, as the domain was created), and fill the sending domain and the From address (at that domain).
  4. In the process editor, add Send batch: Rows {contacts}, To {row.email}, Body Template newsletter.html, and a Custom variable contactId = {row.id}.
  5. Write %unsubscribe_url% in the template's footer for a visible unsubscribe link.
  6. Add a Mailgun start to the same or another process with Failed, Unsubscribed and Marked as spam ticked.
  7. Deploy. The deploy checks the key and domain with Mailgun and adds the Environment's URL to the domain's Mailgun webhooks for the ticked events.
  8. Try the batch with Test mode on: Mailgun accepts and logs the emails without delivering them. Done.

How it works​

Batch sending. Send batch builds the subject and the body once. Every {row.…} placeholder becomes a Mailgun recipient variable (%recipient.r0% in the subject and text, %recipient.h0% HTML-encoded in the HTML part) and each row sends its own values with its address, so a call of up to 1,000 recipients still gives everyone their own copy, and each recipient sees only their own address. Everything else ({month}, {campaign.name}) is filled once for the whole batch.

Events. Mailgun posts every event of the domain to the webhook URLs of the event. The Module checks the signature of each delivery (HMAC-SHA256 of the timestamp and token with the webhook signing key, the timestamp within 15 minutes, each token used once), drops the events the start does not want, starts each remaining event once (Mailgun may send an event twice), and runs the process on the Mailgun channel.

Configuration​

Configure the Module per Environment in its settings.

API key​

Required. An API key of the Mailgun account (API Security → API keys). A domain sending key can send but cannot check the domain, set up webhooks or change suppressions: use an account API key. Stored encrypted.

Region​

EU for domains created in Mailgun's EU region (api.eu.mailgun.net), US otherwise (api.mailgun.net). A wrong region answers Mailgun does not know the domain.

Sending domain​

Required. The domain as Mailgun lists it, for example news.example.com.

From address and From name​

Required: the sender address. Put it at the sending domain (news@news.example.com): with a strict DMARC policy, a From address at another domain fails alignment. The deploy warns when it is not. Send tasks can override both.

Default reply-to​

Optional address replies go to when a Task doesn't set its own.

Webhook signing key​

Required for a Mailgun start: Mailgun → API Security → HTTP webhook signing key. Without it every event is refused. Stored encrypted.

Open tracking and Click tracking​

The default for the send Tasks: Domain setting (the domain's tracking setting in Mailgun applies), On, Off, and for clicks HTML only.

Unsubscribe​

The default for the send Tasks:

  • Mailgun one-click unsubscribe (default): each email asks Mailgun to add List-Unsubscribe and List-Unsubscribe-Post (RFC 8058 one-click). Mailgun records the unsubscribe and sends an unsubscribed event. Write %unsubscribe_url% in the template for a visible link too. Needs the domain's tracking CNAME in Mailgun.
  • Own one-click link: the Task's Unsubscribe link (an https page of yours that unsubscribes with a single POST, per row: https://example.com/unsubscribe?c={row.contactId}) and the optional Unsubscribe mailbox go in the headers.
  • Nothing added: for transactional email, or when the domain's own unsubscribe setting in Mailgun handles it.

Set up Mailgun webhooks on deploy​

On (default): deploying a process with a Mailgun start adds this Environment's URL to the domain's webhooks for the ticked events, takes it off the events no longer ticked, and off all of them when the start is removed. Other URLs on the webhooks are kept (Mailgun allows 3 per event). Off: the deploy only says which URL to add by hand.

Tasks​

MailgunSendBatchTask​

Sends one email per row of a list. While the email is built, the row is a variable, {row} by default.

PropertyRequiredNotes
RowsyesThe {variable} holding the list: Query records, Query file, a SQL query, or a JSON array. At most 10,000 rows.
Each row asnoThe row's name, {row} by default.
ToyesThe row's address, {row.email} by default. One address per row.
Body, Template, Subject, HTML body, Text bodyAs in MailgunSendEmailTask, with {row.…} filled per recipient. The template, Reply-to, From and the attachments are the same for every row.
AttachmentsnoFiles attached to every email. 15 MB.
Unsubscribe, Unsubscribe link, Unsubscribe mailboxnoSee Unsubscribe. The link may read the row.
TagsnoUp to 3, comma-separated; they come back as {mailgun.tags}.
Open / Click trackingnoAdvanced. Module setting by default.
Test modenoMailgun accepts and logs the emails but delivers none.
Deliver atnoAdvanced. Up to 7 days ahead (3 on some Mailgun plans).
Custom variablesnov: values Mailgun returns in every event of the email: contactId = {row.id} arrives as {mailgun.userVariables.contactId}. At most 20.
Custom headersnoAdvanced. h: headers, may read the row.
OutputVariableno{result}: total, accepted, failed, testMode, batches (each call's Mailgun id, messageId, recipients, firstRow) and failures (the first 100 rows not sent, with index, recipient, error).

A row is not sent, and is listed in failures, when its address is empty or invalid, or already appeared in an earlier row (one email per address). Rows go in calls of 1,000 recipients (fewer when the attachments are large, to stay under Mailgun's 25 MB). A call Mailgun rate-limits (429) or answers with a server error is retried with backoff, honouring Retry-After. A call Mailgun refuses for something in its rows (400, 413) is listed as not sent and the next calls still go; a refusal every call would get (the key, the domain, rate limits or server errors after the retries) stops the send, and the remaining rows are listed as not sent. A call that got no answer, or a gateway error (502, 504), is listed as unknown and stops the send: check Mailgun's logs before sending those rows again. The Task takes its error flow only when no email was accepted; otherwise check {result.failed}.

{{#if}} / {{#each}} blocks in a template are filled once for the whole batch, so they can't read the row: write {row.name} instead of {{row.name}}.

MailgunSendEmailTask​

PropertyRequiredNotes
ToyesAddresses separated by commas or semicolons. Accepts {variables}.
Cc / BccnoSame format. At most 50 recipients in total.
BodyyesTemplate, HTML or Text.
Templatewith TemplateA template in Storage → Templates (.html is added if missing).
Subjectwith HTML / TextOverrides the template's <title>.
HTML body / Text bodywith HTML / Text
AttachmentsnoFile fields such as ref-environment:terms.pdf. 10 MB in total.
Reply-to, From address, From namenoDefault to the Module's settings.
Unsubscribe, Tags, tracking, Test mode, Deliver at, Custom variables, Custom headersnoAs in Send batch. Choose Unsubscribe None for transactional email.
OutputVariableno{result.id} (Mailgun's id, with angle brackets), {result.messageId} (as events give it), {result.message}, {result.recipients}.

MailgunSuppressionTask​

PropertyRequiredNotes
OperationyesAdd, Remove or Check.
ListyesUnsubscribes, Bounces or Complaints.
AddressyesThe email address.
TagnoAdd to unsubscribes only: unsubscribe from this tag only. Empty: from everything.
Bounce code / Bounce errornoAdd to bounces only: the SMTP code (550 by default) and reason to record.
OutputVariableno{suppression}: listed, changed, createdAt, tags, code, error.

Checking an address that isn't listed, or removing one that isn't there, is not an error: {suppression.listed} is false.

MailgunStartTask​

Starts the process for the domain's Mailgun events. Tick the events: Delivered, Failed (permanent failure), Delayed (temporary failure), Unsubscribed, Marked as spam, Opened, Clicked. Failed, Unsubscribed and Marked as spam are ticked by default. Delivered, Opened and Clicked start one run per recipient: many runs for a large batch.

Advanced: Only these tags keeps the events of emails with one of the tags (an unsubscribe from everything always matches); Only emails sent from this environment keeps the events of emails this Environment sent with Send email / Send batch, for Environments that share a Mailgun domain (a test Environment next to production).

{mailgun} holds event, eventId, recipient, severity (failed: permanent or temporary), reason, description, code, timestamp, messageId, subject, domain, tags, userVariables, url (clicked), ip, and from (the recipient), to (the sender), channel, isTest.

Test it from the chat with test data, for example {"event": "unsubscribed", "recipient": "ada@example.com", "userVariables": {"contactId": "42"}}.

Common workflows​

Scheduler start (daily 09:00)
→ Query records (contacts where consent = yes and joined_via = campaign) {contacts}
→ Mailgun Send batch (Rows {contacts}, Template newsletter.html, Custom variable contactId = {row.id})
→ Switch on {result.failed} > 0 → Send email (report to the team)
Mailgun start (Unsubscribed, Marked as spam)
→ Update record (contact {mailgun.userVariables.contactId}: consent = no)
Mailgun start (Failed)
→ Switch on {mailgun.severity}: permanent → Update record (email_status = bounced, reason {mailgun.description})
Form start (unsubscribe page)
→ Mailgun Suppression (Add, Unsubscribes, {form.email})

Troubleshooting​

"Mailgun refused the API key (401)"​

The key is wrong, or the Region doesn't match the domain: an EU domain needs Region EU.

"Mailgun does not know 'news.example.com' in the EU region (404)"​

The sending domain is misspelled, belongs to another Mailgun account, or was created in the other region.

"A domain sending key can only send"​

Setting up webhooks, checking the domain and suppressions need an account API key.

Events don't start the process​

Check that the Environment's URL is on the domain's webhooks (Mailgun → Sending → Webhooks), the webhook signing key in the settings is the account's current one, and the event is ticked on the start. A Mailgun webhook keeps at most 3 URLs per event: the deploy says when one is full.

The one-click unsubscribe button doesn't appear in Gmail​

Gmail shows it only for senders it trusts, even with correct headers. Check the email's headers for List-Unsubscribe and List-Unsubscribe-Post, and that the domain passes DMARC.

Reference​

ChannelMailgun (Batch runtime)
Webhook URLPOST {engine}/api/MailgunModule/webhook/{environmentToken}
Recipients per call1,000
Rows per Send batch10,000
Request size25 MB (attachments counted as sent, base64)
Retries5 attempts on 429, 420 and 5xx, honouring Retry-After / X-RateLimit-Reset, at most 60 s apart
Signature tolerance15 minutes; each token once
Webhook answers200 started / ignored / duplicate; 406 for an unknown, deleted or switched-off Environment and for an event of another domain (Mailgun stops retrying); 403 bad or replayed signature; 429 / 503 when the run could not start now or the deployed version has no Mailgun start yet (Mailgun retries for 8 hours)
Engine settingsMailgunModule:WebhooksEnabled (default true), MailgunModule:WebhookPerMinute (default 1200 signed events per Environment), MailgunModule:WebhookPerIpPerMinute (default 6000 requests per caller network, before any lookup)