-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmailgun.ts
55 lines (48 loc) · 1.62 KB
/
mailgun.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import Mailgun, { Interfaces } from 'mailgun.js';
import FormData from 'form-data';
import { providersList } from './providerDetector';
class MailgunWrapper {
mailgun: Interfaces.IMailgunClient | null;
constructor() {
this.mailgun = null;
if (providersList.mailgun.isAvailable) {
this.initialize();
}else{
console.log('Mailgun not available. Missing API key');
}
}
// quote the line abouth api.eu if your mailgun mail server is in the US
private async initialize(){
const mailgunClass = new Mailgun(FormData);
this.mailgun = mailgunClass.client({
username: 'api',
key: process.env.MAILGUN_API_KEY || '',
url: 'https://api.eu.mailgun.net'
});
}
public getMailgun(){
return this.mailgun;
}
public getDefaultValues(){
return {
from: "Paul <[email protected]>",
subject: "Hello",
to: [],
text: "This is me testing emails!"
// html: "<h1>Testing some Mailgun awesomness!</h1>"
}
}
}
// making only one instace of MailgunWrapper for the whole project
const globalForMailgun = globalThis as unknown as { mailgun: MailgunWrapper }
export const mailgunClientGlobal = globalForMailgun.mailgun || new MailgunWrapper()
if (process.env.NODE_ENV !== "production") globalForMailgun.mailgun = mailgunClientGlobal
// how to use in your pages/api routes:
// import { mailgunClientGlobal } from '@/infra/mailgun';
// const mg = await mailgunClientGlobal
// await mg.mailgun?.messages.create(
// 'mail.mydomain.com',
// {...mg.getDefaultValues(),
// from: 'Excited User <[email protected]>',
// to: ['[email protected]'] }
// );