Send an email based on a mailgun template

Fork of hub/1079/mailgun/Send_an_email_based_on_a_mailgun_template

Script mailgun Verified

by aurélien brabant550 · 6/22/2023

The script

Submitted by hugo989 Bun
Verified 4 days ago
1
import formData from "[email protected]";
2
import MailgunClient from "[email protected]";
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

Other submissions
  • Submitted by aurélien brabant550 Deno
    Created 396 days ago
    1
    import formData from "npm:[email protected]";
    2
    import MailgunClient from "npm:[email protected]";
    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