Created
July 17, 2019 09:26
-
-
Save MBing/d91545674aa63210056b7077b96089e6 to your computer and use it in GitHub Desktop.
Sendgrid v3 updated version
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// An example to use the Mailer.js Class | |
const mongoose = require('mongoose'); | |
const Mailer = require('../services/Mailer'); | |
const Survey = mongoose.model('surveys'); | |
app.post('/api/surveys', (req, res) => { | |
const { title, subject, body, recipients } = req.body; | |
const survey = new Survey({ | |
title, | |
body, | |
subject, | |
recipients: recipients | |
.split(',') | |
.map(email => ({ email: email.trim() })), | |
_user: req.user.id, | |
dateSent: Date.now(), | |
}); | |
// Send an email here! | |
const mailer = new Mailer(survey, `<div>${survey.body}</div>`); | |
mailer.send(); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const sgMail = require('@sendgrid/mail'); // separate Node package | |
const helpers = require('@sendgrid/helpers'); // separate Node package | |
const keys = require('../config/keys'); // some place where you store your API keys | |
class Mailer extends helpers.classes.Mail { | |
// Through the use of Static methods from the Mail helper Class, you create a sendgrid compliant instance that can be send easily | |
constructor({ subject, recipients }, content) { | |
super(); | |
this.setFrom('[email protected]'); // uses the EmailAddress.create method | |
this.setSubject(subject); | |
this.addHtmlContent(content); // same as addContent, but more specific for HTML | |
this.recipients = recipients.map(({ email }) => | |
helpers.classes.EmailAddress.create(email) | |
); | |
this.setTrackingSettings({ | |
clickTracking: { enable: true, enableText: true }, | |
}); | |
this.addTo(this.recipients); // This uses the personalization method in the background | |
} | |
// To separate our data from what we send out, we create another function | |
async send() { | |
sgMail.setApiKey(keys.sendGridKey); | |
return await sgMail.send(this); // attach the current instance to be send out with SendGrid | |
} | |
} | |
module.exports = Mailer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment