-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathemail.ts
78 lines (69 loc) · 1.73 KB
/
email.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
'use server';
import AWS from 'aws-sdk';
import { render as renderTemplate, Data as TemplateData } from 'template-file';
const client = new AWS.SES({
apiVersion: '2010-12-01',
region: process.env.AWS_REGION ?? 'us-east-1',
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID ?? '',
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY ?? '',
},
});
export interface Email {
replyTo?: string | string[];
to: string | string[];
subject: string;
body: string;
isHtml?: boolean;
}
export async function sendEmail({
to,
replyTo,
subject,
body,
isHtml = false,
}: Email): Promise<boolean> {
const fromAddr = process.env.EMAIL_FROM;
if (!fromAddr) {
console.error('No FROM email address provided');
return false;
}
try {
const params: AWS.SES.SendEmailRequest = {
Source: fromAddr,
ReplyToAddresses: Array.isArray(replyTo)
? replyTo
: [replyTo ?? fromAddr],
Destination: {
ToAddresses: Array.isArray(to) ? to : [to],
},
Message: {
Subject: {
Data: subject,
},
Body: {
[isHtml ? 'Html' : 'Text']: {
Data: body,
},
},
},
};
const resp = await client.sendEmail(params).promise();
if (resp.$response.error) throw new Error(resp.$response.error.message);
} catch (e) {
console.error(`Failed to send email with parameters ${e}`);
return false;
}
return true;
}
export interface TemplateEmail extends Email {
templateData: TemplateData;
}
/**
* @see https://github.com/gsandf/template-file
*/
export const sendTemplateEmail = async (e: TemplateEmail): Promise<boolean> =>
sendEmail({
...e,
body: renderTemplate(e.body, e.templateData),
});