Skip to content

Instantly share code, notes, and snippets.

@MBing
Created July 17, 2019 09:26
Show Gist options
  • Save MBing/d91545674aa63210056b7077b96089e6 to your computer and use it in GitHub Desktop.
Save MBing/d91545674aa63210056b7077b96089e6 to your computer and use it in GitHub Desktop.
Sendgrid v3 updated version
// 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();
});
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('no-reply@emaily.com'); // 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