1
Send an email based on a mailgun template
One script reply has been approved by the moderators Verified

Fork of hub/1079/mailgun/Send_an_email_based_on_a_mailgun_template

Created by aurélien brabant550 532 days ago Viewed 11157 times
0
Submitted by aurélien brabant550 Deno
Verified 532 days ago
1
import formData from "npm:form-data@4.0.0";
2
import MailgunClient from "npm:mailgun.js@9.1.0";
3

4
interface Mailgun {
5
  api_key: string;
6
}
7

8
export async function main(
9
  mailgunConfig: Mailgun,
10
  domain: string,
11
  from: string,
12
  to: string[],
13
  subject: string,
14
  templateName: string,
15
  replyTo?: string,
16
  substitutions: Record<string, string>,
17
) {
18
  const mailgun = new MailgunClient(formData);
19
  const mg = mailgun.client({ username: "api", key: mailgunConfig.api_key });
20

21
  try {
22
    const result = await mg.messages.create(domain, {
23
      from,
24
      to,
25
      subject,
26
      template: templateName,
27
      "h:X-Mailgun-Variables": JSON.stringify(substitutions),
28
      ...(replyTo && { "h:Reply-To": replyTo }),
29
    });
30

31
    return result;
32
  } catch (error) {
33
    console.error(error);
34
    throw error;
35
  }
36
}
37