-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathemail-nodemailer.js
71 lines (63 loc) · 2.41 KB
/
email-nodemailer.js
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
/*
--------------------------------------------------------------------------------
- lib/email-nodemailer.js
--------------------------------------------------------------------------------
*/
const nodemailer = require('nodemailer');
/* createTransport() create reusable transporter object using the default
SMTP transport
*/
function createTransport() {
const environmentVariable = [
'NODEMAILER_HOST', // e.g. smtp.gmail.com
'NODEMAILER_PORT', // e.g. 465
'NODEMAILER_EMAIL', // e.g. [email protected]
'NODEMAILER_EMAIL_PW',
];
for (let i = 0; i < environmentVariable.length; i += 1) {
const ev = process.env[environmentVariable[i]];
if (!ev) {
return {
sendMail: () => {
throw new Error(
`Missing environment variable ${environmentVariable[i]}!`,
);
},
};
}
}
return nodemailer.createTransport({
host: process.env.NODEMAILER_HOST, // e.g. 'smtp.ethereal.email'
port: process.env.NODEMAILER_PORT, // e.g. 465
secure: process.env.NODEMAILER_SECURE !== 'false', // In dev, it can be useful to turn this off, e.g. to work with ethereal.email
auth: {
user: process.env.NODEMAILER_EMAIL,
pass: process.env.NODEMAILER_EMAIL_PW,
},
});
}
async function sendEmail(message) {
if (process.env.SUPPRESS_EMAIL) return;
const transport = createTransport();
const params = {
from: {
name: message.fromName, // If not provided, undefined value is ignored just fine by nodemailer
address: process.env.NODEMAILER_EMAIL,
},
to: message.toAddress, // list of receivers e.g. '[email protected], [email protected]'
subject: message.subject,
// text: 'Hello world?', // plain text body
html: message.body, // html body
headers: {
// This is the correct header for tags if sending to an AWS SES SMTP endpoint.
// Any other SMTP server will probably ignore this header.
'X-SES-MESSAGE-TAGS': message.tags.join(', '),
},
};
if (message.ccAddress) {
params.cc = message.ccAddress;
}
await transport.sendMail(params);
}
module.exports = { sendEmail };
/* * * * */