I'm using Advanced Scheduler in Heroku to try scheduleding a task that is send an email every day at 10 AM. The command that executes is npm start, because whenever the app runs it executes a determined request that it's purpose it's only to send an email.
To send this email I use nodemailer and smtp service called smtp2go and in the localhost using cron runs with no problem. My problem is when is the Advanced Scheduler executing is task. When the task is executed it sends two email instead of just one. I read that the best it's to implement async and await to the function, but it didn't solved my problem.
const express = require('express');
const nodemailer = require('nodemailer');
let cron = require('node-cron');
var rp = require('request-promise');
var cors = require('cors');
var sleep = require('system-sleep');
const app = express();
const port = process.env.PORT || 3000;
const bodyParser = require('body-parser');
const transporter = nodemailer.createTransport({
host: 'mail.smtp2go.com',
port: 2525,
secureConnection: false,
requireTLS: true,
auth: {
user: 'xxx',
pass: 'xxxx'
},
tls: {
ciphers:'SSLv3'
}
});
app.use(bodyParser.json());
app.use((req, res, next) => {
req.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
res.header("Access-Control-Allow-Methods", "GET, POST","PUT", "DELETE");
next();
});
app.post('/kitty', async function handler(req, res) {
var apiKey = 'xxxxxxxx';
const baseUrl = "xxxxx";
const baseUrl1 = "xxxxxxx";
var options = {
uri: baseUrl,
method: 'GET',
json: true,
headers: {
'x-api-key': apiKey
}
};
var options1 = {
uri: baseUrl1,
method: 'GET',
json: true,
}
rp(options)
.then(function (resp) {
rp(options1)
.then(function (resp1) {
let mailOptions = {
from: 'xxxxx@gmail.com',
to: 'xxx@gmail.com',
subject: 'xxxxxxx!',
html: '<h1>xxxxxxx</h1>',
attachments: [
{
filename: 'Cutecat.png',
path: resp[0]["url"]
}
]
};
sleep(5000);
transporter.sendMail(mailOptions, function (error, response) {
if (error) {
console.log(error);
res.end('error');
} else {
console.log('Message sent: ', response);
res.end('sent');
}
});
});
});
});
app.listen(port, function () {
console.log('Express started on port: ', port);
Urltest = 'http://localhost:3000/kitty';
Url = 'https://smtp-tufinho.herokuapp.com/kitty';
var options = {
uri: Url,
method: 'POST',
json: true,
};
rp(options).then(function () {
console.log("exit");
process.exit(0);
});
});