Send multi-user emails with nodemailer and gmail
I am trying to send an email to multiple recipients (about 3.000). All emails are stored in my DB (Mongo). So I am making a request that returns all email addresses and I am using async to send all email messages, like this:
function _sendEmail(params, callback) {
async.each(params.email, function(user, cb) {
const mailOptions = {
from: sender
to: user,
subject: Subject,
text: 'Hello Word',
};
app.transporter.sendMail(mailOptions, function(err, response) {
if(err) console.log(err);
else console.log(response);
cb();
});
}, callback);
}
I am creating my nodemailer port in my app.js app, for example:
const transporter = nodemailer.createTransport(smtpTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: senderMail,
pass: senderMailPassword
}
}));
When I try to send this to only 10 emails, it works fine, but when I try to send all emails in my DB I get this error multiple times:
{ [Error: Data command failed: 421 4.7.0 Temporary System Problem. Try again later (WS). g32sm7412411qtd.28 - gsmtp]
code: 'EENVELOPE',
response: '421 4.7.0 Temporary System Problem. Try again later (WS). g32sm7412411qtd.28 - gsmtp',
responseCode: 421,
command: 'DATA' }
Am I missing something? Should I install something to send many os emails in a small amount of time? I use a gmail account for this!
Thanks in advance!
source to share
This is because you are trying to create a new SMTP connection for each email. You need to use an SMTP pool. Pooled SMTP is mostly useful when you have a large number of messages that you want to send in batches, or your ISP only allows you to use a small number of concurrent connections.
const transporter = nodemailer.createTransport(smtpTransport({
host: 'smtp.gmail.com',
port: 465,
pool: true, // This is the field you need to add
secure: true,
auth: {
user: senderMail,
pass: senderMailPassword
}
}));
You can close the pool like
transporter.close();
source to share