/
index.ts
62 lines (54 loc) · 1.34 KB
/
index.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
import {google} from 'googleapis'
import MailComposer from 'nodemailer/lib/mail-composer'
import connect from './connect'
const validFrom = [
'sistema@cruzrepresentacoes.com.br',
'e-commerce@cruzrepresentacoes.com.br'
]
export function sendMail(
subject: string,
text: string,
to: string[],
from: string = validFrom[0],
attachment?: {name: string; file: any}
) {
const mail = new MailComposer({
from: `Cruz Representacoes <${from}>`,
to: to.join(', '),
text: text,
html: text,
subject: subject,
textEncoding: 'base64',
attachments: attachment
? [
{
filename: attachment.name,
content: attachment.file,
encoding: 'base64'
}
// eslint-disable-next-line no-mixed-spaces-and-tabs
]
: []
})
mail.compile().build((error, msg) => {
if (error) console.error('<< error compiling mail >>', error)
const encodedMessage = Buffer.from(msg)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '')
async function callback(auth: any) {
const gmail = google.gmail({version: 'v1', auth})
await gmail.users.messages
.send({
userId: 'me',
requestBody: {
raw: encodedMessage
}
})
.then(res => console.log('<< res.data >>', res.data))
.catch(error => console.error('<< error sending message >>', error))
}
connect(callback)
})
}