I want to be able to delay send email on my heroku/nodejs app. I know how to use the Heroku Scheduler to delay tasks. I can then retrieve which emails need to be sent for which user. But to use the Gmail API I need to retrieve the authenticated user session, and I don't know how to do that. I am using pg to store the session, but I don't believe it would be specific:
app.use(session({ secret: 'xxx', store: new pgSession({ conString: config.db.url }), resave: false, saveUninitialized: false, cookie: { maxAge: 24192000000 } }));
2 Answers
Answers 1
High Level
At some point there is a function along your route chain that is triggering the delayed email, you should just include the session (from req.session
) in the task register. From there just make sure the proper user data is available for you to send the email (aka, user_id or user_email in the session data).
More Detailed
You need to think about how your middleware is handling this for a moment.
app.use(session({
etc. is going to add a session
object to your req
object. Somewhere in your routes, you are processing another function (such as login or registration) after the app.use (session)
portion is called. So in the case of Gmail, you are calling an Oauth request to the Gmail api. They are going to return a user access token to you, which you can use to fetch their user data (such as email address). From there, you can attach their user data to your req.session
object.
A Simple Example (modify for your use)
app.use(session({ secret: 'xxx', store: new pgSession({ conString: config.db.url }), resave: false, saveUninitialized: false, cookie: { maxAge: 24192000000 } })); app.post('/register', function(req, res, next) { // You'll have to write your own google client implementation :) var token = getGoogleAccessToken(); // Again, left to you to write. var user_email = fetchUserGoogleEmail( token ); var session = req.session; session.email = user_email; // Register heroku delayed task with session data. // Save user data and create account, etc. });
Answers 2
I use the below code to do something similar
var email = require("emailjs"); var server = email.server.connect({ user: "user@gmail.com", password: "password", host: "smtp.gmail.com", ssl: true }); var cron = require('node-schedule'); cron.scheduleJob({hour: 2, minute: 30, dayOfWeek: 0}, function() { server.send({ text: "i hope this works", from: "you <user@gmail.com>", to: "reciever <reciever@gmail.com>", subject: "My Email Subject" }, function(err, message) { //error handling }); });
hope this helps
0 comments:
Post a Comment