Back to APIs

Send, retrieve and delete emails, manage domains, and more.

Using the Mailgun API with Trigger.dev

You can use Trigger.dev with any existing Node SDK or even just using fetch. Using io.runTask makes your Mailgun background job resumable and appear in our dashboard.

Use io.runTask() and the official SDK or fetch.

Use our HTTP endpoint to subscribe to webhooks

Example code using Mailgun

Below are some working code examples of how you can use Mailgun with Trigger.dev. These samples are open source and maintained by the community, you can copy and paste them into your own projects.

1
import { TriggerClient, eventTrigger } from "@trigger.dev/sdk";
2
import { z } from "zod";
3
const formData = require("form-data");
4
const Mailgun = require("mailgun.js");
5
6
// https://documentation.mailgun.com/en/latest/quickstart-sending.html#how-to-start-sending-emaild
7
// after login from https://app.mailgun.com/mg/dashboard -> setting you can get api, and private_api_key
8
const mailgun = new Mailgun(formData);
9
const mg = mailgun.client({
10
username: process.env.MAILGUN_API_KEY_ID,
11
key: process.env.MAILGUN_PRIVATE_API_KEY,
12
});
13
14
client.defineJob({
15
id: "mailgun-send-email",
16
name: "Mailgun send email",
17
version: "1.0.0",
18
trigger: eventTrigger({
19
name: "mailgun.send.email",
20
schema: z.object({
21
sandboxDomain: z.string(), // for sandboxdomain -> https://app.mailgun.com/mg/dashboard
22
emailTo: z.string().email(),
23
subject: z.string(), // email subject
24
text: z.string(), // email content
25
}),
26
}),
27
28
run: async (payload, io, ctx) => {
29
// Wrap an SDK call in io.runTask so it's resumable and displays in logs
30
const user = await io.runTask(
31
"Send Email",
32
async () => {
33
return await mg.messages.create(payload.sandboxDomain, {
34
from: `Mailgun Sandbox <postmaster@${payload.sandboxDomain}>`,
35
to: [payload.emailTo],
36
subject: payload.subject,
37
text: payload.text,
38
});
39
},
40
41
// Add metadata to improve how the task displays in the logs
42
{ name: "Send Email by Mailgun", icon: "mailgun" }
43
);
44
},
45
});