This repository has been archived by the owner on Nov 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sendEmail.ts
79 lines (71 loc) · 1.83 KB
/
sendEmail.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import * as nodemailer from 'nodemailer'
import * as mg from 'nodemailer-mailgun-transport'
import { EmailNotificationTypes } from '../../src/types/types'
/**
*
* @description
* Function to send our notification emails. These rely on
* templates stored in MailGun which contain the majority of
* the templating and styling, along with static text.
*
* Dynamic values such as reset tokens, etc are passed in the
* `options.email.templateData` parameter as an object.
*
* @example
* ```
* await sendNotification(message, {
* channels: ['email'],
* email: {
* token
* to: user.email,
* subject: 'Reset your password',
* template: TEMPLATE_RESET_PASSWORD,
* templateData: {
* link,
* },
* apiKey: process.env.MAILGUN_API_KEY,
* domain: process.env.MAILGUN_DOMAIN
* },
* })
* ```
*/
let mailer
class EmailNotifier {
options: object
apiKey: string
domain: string
constructor(options: EmailNotificationTypes) {
this.apiKey = options.apiKey
this.domain = options.domain
this.options = {
auth: {
api_key: this.apiKey,
domain: this.domain,
},
}
if (!mailer) {
mailer = nodemailer.createTransport(mg(this.options))
}
}
sendEmail = async (options: EmailNotificationTypes) => {
const auth = {
auth: {
apiKey: this.apiKey,
domain: this.domain,
},
}
try {
await mailer.sendMail({
from: '[email protected]',
to: options.to,
subject: options.subject,
template: options.template,
'h:X-Mailgun-Variables': JSON.stringify(options.templateData),
})
return 'Email notification sent successfully.'
} catch (error) {
throw new Error(`Email notification failed to send: ${error}`)
}
}
}
export default EmailNotifier