-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
223 lines (185 loc) · 6.79 KB
/
mod.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import { Client, Options, SendData, TemplateData, Type } from './types.ts';
import { encode, typeByExtension } from './deps.ts';
import * as Html from './html.ts';
import * as Text from './text.ts';
// import jwt from './jwt.ts';
// type Key = {
// type?: string;
// project_id?: string;
// private_key_id?: string;
// private_key: string;
// client_email: string;
// client_id?: string;
// auth_uri?: string;
// token_uri?: string;
// auth_provider_x509_cert_url?: string;
// client_x509_cert_url?: string;
// };
export default class Email {
#key?: any;
#type: Type = 'json';
#client?: Client;
#sandbox: boolean = false;
constructor(options?: Options) {
this.#key = options?.key ?? this.#key;
this.#client = options?.client ?? this.#client;
this.#type = options?.type ?? this.#type;
this.#sandbox = options?.sandbox ?? this.#sandbox;
}
#sendGrid(data: SendData) {
if (!this.#key) throw new Error('key required');
const body: any = {
content: [],
subject: data.subject,
from: { email: data.from },
personalizations: [],
};
if (this.#sandbox === true) {
body.mail_settings = { sandbox_mode: { enable: true } };
}
if (data.to?.constructor === String) {
body.personalizations.push({ to: [{ email: data.to }] });
}
if (data.to?.constructor === Array) {
body.personalizations.push({
to: data.to.map((email) => ({ email })),
});
}
if (data.name) body.from.name = data.name;
// if (data.reply) body.replay_to = { email: data.reply };
if (data.text) {
body.content.push({ type: 'text/plain', value: data.text });
}
if (data.html) {
body.content.push({ type: 'text/html', value: data.html });
}
if (data.attachments) {
body.attachments = [];
if (data.attachments?.constructor !== Object) {
throw new Error('attachments object type not valid');
}
for (const name in data.attachments) {
const value = data.attachments[name];
body.attachments.push({
filename: name,
content: encode(value),
disposition: 'attachment',
type: typeByExtension(name),
});
}
}
return fetch('https://api.sendgrid.com/v3/mail/send', {
method: 'POST',
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.#key}`,
},
});
}
// #token?: string;
// #expires?: number;
// async #auth () {
// if (this.#expires && this.#expires >= Date.now()) return;
// let response;
// if (this.#key) {
// const iss = this.#key.client_email;
// const iat = Math.round(Date.now() / 1000);
// const exp = iat + (30 * 60);
// const aud = 'https://oauth2.googleapis.com/token';
// const scope = 'https://www.googleapis.com/auth/datastore';
// const assertion = await jwt({ typ: 'JWT', alg: 'RS256', }, { exp, iat, iss, aud, scope }, this.#key.private_key);
// response = await fetch('https://oauth2.googleapis.com/token', {
// method: 'POST',
// body: [
// `assertion=${encodeURIComponent(assertion)}`,
// `grant_type=${encodeURIComponent('urn:ietf:params:oauth:grant-type:jwt-bearer')}`
// ].join('&'),
// headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
// });
// } else {
// response = await fetch('http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token', {
// method: 'GET',
// headers: { 'Metadata-Flavor':'Google' }
// });
// }
// const result = await response.json();
// if (result.error) {
// throw new Error(JSON.stringify(result.error, null, '\t'));
// }
// this.#token = result.access_token;
// this.#expires = Date.now() + (result.expires_in * 1000);
// }
// #gmail (data: Data) {
// if (!this.#key) throw new Error('key required');
// this.#auth();
// const raw = btoa(
// "From: [email protected]\r\n" +
// "To: [email protected]\r\n" +
// "Subject: Subject Text\r\n\r\n" +
// "The message text goes here"
// ).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
// return fetch('https://gmail.googleapis.com/gmail/v1/users/alex.steven.elias%40gmail.com/messages/send', {
// method: 'POST',
// body: JSON.stringify({
// raw
// }),
// headers: {
// 'Accept': 'application/json',
// 'Content-Type': 'application/json',
// 'Authorization': `Bearer ${this.#token}`
// }
// });
// }
key(key: string) {
this.#key = key;
return this;
}
client(client: Client) {
this.#client = client;
return this;
}
type(type: Type) {
this.#type = type;
return this;
}
sandbox(sandbox: boolean) {
this.#sandbox = sandbox;
return sandbox;
}
template(data: TemplateData) {
if (typeof data.content !== 'object') {
throw new Error('content not valid');
}
const textLines = [];
const htmlLines = [];
const csvHead = [];
const csvLine = [];
for (const name in data.content) {
const value = data.content[name];
htmlLines.push(Html.line(name, value));
textLines.push(Text.line(name, value));
csvHead.push(name);
csvLine.push(value);
}
const text = Text.body(data, textLines);
const html = Html.body(data, htmlLines);
const attachments = {
'data.csv': `${csvHead.join(',')}\n"${csvLine.join('","')}"`,
};
return { text, html, attachments };
}
send(data: SendData) {
if (!data) throw new Error('data required');
if (!data.to) throw new Error('to required');
if (!data.from) throw new Error('from required');
data = { ...data };
switch (this.#client) {
// case 'gmail': return this.#gmail(data);
case 'sendgrid':
return this.#sendGrid(data);
default:
throw new Error('client required');
}
}
}