Skip to content

Commit

Permalink
email template ;; mailer --- all the mail.(....) is sendgrid api
Browse files Browse the repository at this point in the history
  • Loading branch information
rohan-git committed Nov 28, 2017
1 parent b8078a0 commit 2e5fdf0
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 0 deletions.
9 changes: 9 additions & 0 deletions routes/surveyRoutes.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
const mongoose = require('mongoose');

const requireLogin = require('../middlewares/requireLogin');
const requireCredits = require('../middlewares/requireCredits');

const mailer = require('../services/Mailer');
const surveyTemplate = require('../services/emailTemplate');

const Survey = mongoose.model('Survey');

module.exports = app => {
Expand All @@ -20,6 +24,11 @@ module.exports = app => {
dateSent: Date.now(),
});

// send survey email right after it gets saved
const mailer = new Mailer(survey, surveyTemplate(survey));



});

};
71 changes: 71 additions & 0 deletions services/Mailer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
const passport = require('sendgrid');
const helper = sendgrid.mail; // `helper` name is used thruout sendgrid documentation

const keys = require('../config/keys');


class Mailer extends helper.Mail {

// can be any obj with {subject, recipients}
// used with Survey db model to pull these 2 properties from it
constructor({subject, recipients}, content){
super();

this.sgAPI = sendgrid(keys.sendGridKey);

this.from_email = new helper.Email('[email protected]');
this.subject subject;
this.body = new helper.Content('text/html', content);
this.recipients = this.formatAddresses(recipients);

this.addContent(this.body);

this.addClickTracking();
this.addRecipients();
}

formatAddresses(recipients){

return recipients.map({email}) => {
return new helper.Email(email);
}
}

addClickTracking(){

const trackingSettings = new helper.TrackingSettings();
const clickTracking = new helper.ClickTracking(true, true);

trackingSettings.setClickTracking(clicktracking);
this.addTrackingSettings(trackingSettings);

}

addRecipients(){

const personalize = this.recipients.forEach(recipient => {

personalize.addTo(recipient);

});

this.addPersonalization(personalize);

}

async send(){

const request = sgAPI.emptyRequest({
method: 'POST',
path: 'v3/mail/send',
body: this.toJSON()
});

const response = await this.sgAPI.API(request);
return response;

}
}


module.exports = Mailer;
5 changes: 5 additions & 0 deletions services/emailTemplate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = (survey) => {

return ( "<div> Hello " + survey.body + " </div>" );

};

0 comments on commit 2e5fdf0

Please sign in to comment.