Send multipe emails using nodemailer and gmail

2019-09-14 05:41发布

I am trying to send an email to multiple recipients ( about 3.000 ). All emails are stored in my DB ( Mongo ). So I make a query that return all the email addresses, and I use async to send all the emails, like:

    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 transporte in my app.js, ,like so:

    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 mails, it works just fine, but when I try to send to all the emails in my DB, I am getting this error a bunch of 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? Do I need to set something to be able to send lots os emails in a small period of time? I am using a gmail account to do that!

Thanks in advance!

2条回答
狗以群分
2楼-- · 2019-09-14 06:29

From Gmail : 421 SMTP Server error: too many concurrent sessions

You may handle your send differently :

  • wait to close the session between each sending

  • send by bunch of mail

The best way is to manage to not exceed the limit of 10 session in the same time :)

查看更多
Animai°情兽
3楼-- · 2019-09-14 06:35

It is because you are attempting to create a new smtp connection for each email. You need to use SMTP pool. Pooled smtp is mostly useful when you have a large number of messages that you want to send in batches or your provider allows you to only use a small amount of parallel 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 as

transporter.close();
查看更多
登录 后发表回答