2

I have a scheduled job that I need to send daily emails out to customers.

Right now I am just testing the basic framework that I will use so I have Node Heroku Scheduler trying to send a test email every 10 minutes using the Mandrill API.

In normal operating situations I can send the test email successfully using the following back-end code:

Controller:

sendTestEmail: function (req, res) {

console.log("Trying to send the hourly email.");

var emailInfo = {
    message: "Sample Message - should send hourly.",
    subject: "Hourly email test",
    fromEmail: "collegepregame@gmail.com",
    fromName: "SmallChangeProject",
    to: "zach_cook@texasca.com",
    name: "Zachary Cook"
};

EmailService.simpleSendEmail(emailInfo, function(err, message) {
    if (err) {
        console.log("Email did not send.", err);
        res.send(404, '\n\nerror occurred\n\n');
    }

    console.log("Message sent: ", message);
    return res.send(message);
});

}

That EmailService code looks like this:

Service:

var mandrill = require('mandrill-api/mandrill');
var mandrill_client = new mandrill.Mandrill('dDIJDHIDDEN2893KEYUNDSECRET');

module.exports = {

  simpleSendEmail: function (emailInfo, cb) {

    var message = {
      "html": emailInfo.message || "Accidental email, please ignore",
      "text": emailInfo.text || "Example text content",
      "subject": emailInfo.subject || "Password Reset Email",
      "from_email": emailInfo.fromEmail || "customerservice@smallchangeproj.com",
      "from_name": emailInfo.fromName || "SmallChangeProject",
      "to": [{
        "email": emailInfo.to || "zacharycook2014@utexas.edu",
        "name": emailInfo.name || 'Name Unavailable'
      }],
      "headers": {
        "Reply-To": emailInfo.fromEmail || "customerservice@smallchangeproj.com"
      },
      "important": false,
      "track_opens": null,
      "track_clicks": null,
      "auto_text": null,
      "auto_html": null,
      "inline_css": null,
      "url_strip_qs": null,
      "preserve_recipients": null,
      "view_content_link": null,
      "tracking_domain": null,
      "signing_domain": null,
      "return_path_domain": null,
      "merge": true,
      "merge_language": "mailchimp"
    };
     var async = false;
     var ip_pool = "Main Pool";

     // console.log('\n-------\nprenteding to send the emails!\n-------\n');
    mandrill_client.messages.send({"message": message, "async": async, "ip_pool": ip_pool}, function(result) {
      console.log(result);
    }, function(e) {
      // Mandrill returns the error as an object with name and message keys
      console.log('A mandrill error occurred: ' + e.name + ' - ' + e.message);
      return cb('an error occurred');
      // A mandrill error occurred: Unknown_Subaccount - No subaccount exists with the id 'customer-123'
    });

    return cb(null, 'email has been sent');

  }

};

Ok so all of that works. The problem is when I try to send it using a scheduled job.

I borrowed a concept from this StackOverflow post and the Gitter channel for SailsJS where I asked for help. I was recommended to use Sails.lift() to get my scheduled job to be able to operate in the environment is supposed to in order to use all my regular controllers, models, and services.

UPDATED - I PUT ALL CODE IN THE SAME FILE TO HELP TROUBLESHOOT

That code looks like so:

var Sails = require('sails');
var mandrill = require('mandrill-api/mandrill');
var mandrill_client = new mandrill.Mandrill('W9IVcGVz1E1oTmvG_KdiXQ');

Sails.lift(function(err, sails) {

    console.log("Trying to send the hourly email.");
    if (mandrill) {
        console.log("Have mandrill itself.");
    }

    if (mandrill_client) {
        console.log("Have mandrill client initiated.");
    }

    var emailInfo = {
      message: "Sample Message - should send hourly.",
      subject: "Hourly email test",
      fromEmail: "collegepregame@gmail.com",
      fromName: "SmallChangeProject",
      to: "zach_cook@texasca.com",
      name: "Zachary Cook"
    };

    var message = {
      "html": emailInfo.message || "Accidental email, please ignore",
      "text": emailInfo.text || "Example text content",
      "subject": emailInfo.subject || "Password Reset Email",
      "from_email": emailInfo.fromEmail || "customerservice@smallchangeproj.com",
      "from_name": emailInfo.fromName || "SmallChangeProject",
      "to": [{
        "email": emailInfo.to || "zacharycook2014@utexas.edu",
        "name": emailInfo.name || 'Name Unavailable'
      }],
      "headers": {
        "Reply-To": emailInfo.fromEmail || "customerservice@smallchangeproj.com"
      },
      "important": false,
      "track_opens": null,
      "track_clicks": null,
      "auto_text": null,
      "auto_html": null,
      "inline_css": null,
      "url_strip_qs": null,
      "preserve_recipients": null,
      "view_content_link": null,
      "tracking_domain": null,
      "signing_domain": null,
      "return_path_domain": null,
      "merge": true,
      "merge_language": "mailchimp"
    };
    var async = false;
    var ip_pool = "Main Pool";

    mandrill_client.messages.send({"message": message, "async": async, "ip_pool": ip_pool}, function(result) {
        console.log(result);
        console.log("Should have sent!");
    }, function(e) {
      console.log('A mandrill error occurred: ' + e.name + ' - ' + e.message);
    });

    console.log("Email should have sent.");

    process.exit();
});

In the console that gives me:

 Starting process with command `node scheduled-job.js` scheduler@addons.heroku.com
 heroku[scheduler.1963]: Starting process with command `node scheduled-job.js`
 heroku[scheduler.1963]: State changed from starting to up
 app[scheduler.1963]: Trying to send the hourly email.
 app[scheduler.1963]: Have mandrill itself.
 app[scheduler.1963]: Have mandrill client initiated.
 app[scheduler.1963]: Email should have sent.
 heroku[scheduler.1963]: State changed from up to complete
 heroku[scheduler.1963]: Process exited with status 0

The success messages make it seem like everything works and EmailService.simpleSendEmail() doesn't give me any errors - but no email is sent out.

What is the reason it is not sending, yet Mandrill gives me no error message? Will sails.lift() not work for sending scheduled emails?

Thanks for any/all help!

Best - Zach

Community
  • 1
  • 1
Zach Cook
  • 604
  • 12
  • 33

1 Answers1

2

Your process.exit() killed the scheduled task before the email could be sent. Try taking that out. If necessary you can call process.exit() in the callback where you get the result from the API call.

Jason Livesay
  • 6,317
  • 3
  • 25
  • 31