email.js:
function send() {
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'password'
}
});
var mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'Revenue Report',
text: "Hello"
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent Successfully' + info.response);
}
});
}
module.exports = {
send
}
var input = require('readline-sync');
var choice = input.questionInt("Enter Choice: ");
while (choice == 1) {
var mail = require('./email.js');
mail.send();
break;
}
What I am trying to do is execute nodemailer to send an email to my gmail in a while loop. Although I can use if statement, I want to use while loop for other purposes, this is just an example.
In addition, I'm not sure why if statement is able to fully execute the code but not while loop. In while loop, the code just got stucked there and did not execute anything. However, in if statement, it got executed and an email was sent to my gmail.
That is just what I have found out during my troubleshooting process. I have researched and it says that I have to use async / await so that it will suspend the while loop and allow other events to process while waiting for the promise to resolve ? I don't quite understand that and was wondering if it can be done. Please help
async function send() {
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'wervqojdwsnlgrzy'
}
});
var mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'Revenue Report',
text: "Hello"
};
const info = await transporter.sendMail(mailOptions);
console.log('Email sent Successfully' + info.response);
}
module.exports = {
send
}
I have tried the code above but couldn't make it to work.
.sendMail()
uses a callback because network communication is asynchronous. 2. without that break; statement your code would attempt to send thousands of emails in a few milliseconds 3. here's a primer I wrote on async / await: jsfiddle.net/khrismuc/kpj204wL - ChrisGconst info = await transporter.sendMail(mailOptions);
. Also, declare the function likeasync function send() { ... }
- ChrisG