forked from sendgrid/sendgrid-nodejs-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmtp-nodejs-example.js
58 lines (50 loc) · 1.51 KB
/
smtp-nodejs-example.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
var dotenv = require('dotenv');
dotenv.load();
var nodemailer = require('nodemailer');
var smtpapi = require('smtpapi');
var sendgrid_username = process.env.SENDGRID_USERNAME;
var sendgrid_password = process.env.SENDGRID_PASSWORD;
var to = process.env.TO;
// Build the smtpapi header
var header = new smtpapi();
header.addSubstitution('%how%', ['Owl']);
// Add the smtpapi header to the general headers
var headers = { 'x-smtpapi': header.jsonString() };
// Use nodemailer to send the email
var settings = {
host: "smtp.sendgrid.net",
port: parseInt(587, 10),
requiresAuth: true,
auth: {
user: sendgrid_username,
pass: sendgrid_password
}
};
var smtpTransport = nodemailer.createTransport(settings);
var mailOptions = {
from: to,
to: to,
subject: "[smtp-nodejs-example] Owl",
text: "%how% are you doing?",
html: "<strong>%how% are you doing?</strong>",
attachments: {
path: './gif.gif',
filename: 'owl.gif'
},
headers: headers
}
smtpTransport.sendMail(mailOptions, function(error, response) {
smtpTransport.close();
if (error) {
console.log(error);
}
else {
console.log("Message sent: ");
console.log("-------------------------");
console.log("Accepted: " + response.accepted);
console.log("Rejected: " + response.rejected);
console.log("Response: " + response.response);
console.log("Envelope: " + JSON.stringify(response.envelope));
console.log("MessageId: " + response.messageId);
}
});