Create a definition file e.g. your-app/definitions/newsletter.js
:
function newsletter(callback, page) {
// Example uses PostgreSQL/MySQL/SQLServer/MongoDB database with SQL Agent module
var sql = DB();
if (!page)
page = 1;
sql.select('users', 'tbl_user').make(function(filter) {
// Reads 100 users per page
filter.page(page, 100);
filter.where('newsletter', true);
filter.fields('firstname', 'email');
});
sql.exec(function(err, response) {
// No users === end
if (!response.users.length)
return callback();
// Sends 15 emails together
response.users.limit(15, function(users, next) {
var messages = [];
for (var i = 0, length = users.length; i < length; i++) {
var user = users[i];
var message = Mail.create('Our new newsletter', F.view('mails/newsletter', user));
message.to(user.email);
message.from('info@totaljs.com', 'Total.js framework');
// Adds the message to pending list
messages.push(message);
}
// The method below sends multiple email messages in the single connection
Mail.send2(messages, function(err, count) {
// Next 15 emails
next();
});
}, () => newsletter(callback, page + 1)); // processes next page
});
}
// Creates a scheduler
F.schedule('09:00', '1 week', () => newsletter(NOOP));