1

I am using nodejs with nodemailer for sending emails to users.

I have a list of users like this :-

[
  {
    name: "John Doe",
    email: "john@something.com"
  }, 
  { 
    name: "Jane Doe",
    email: "jane@something.com"
  }
  ...and more.
]

How can I send email to all the users in array using nodemailer.

See my code -

users.map(user => {
          const mailOptions = {
              from: '*****@gmail.com',
              to: user.email,
              subject: subject, // Any subject
              text: message // Any message
          }

          transporter.sendMail(mailOptions, (err, info) => {
              if (err) {
                  console.log(err)
              } else {
                  console.log(info)   
              }
          })
   })

Is this a correct way of doing this ?

Thanks in advance !

The Plier
  • 35
  • 4

2 Answers2

0

Convert the array of emails to a comma separated string

const recipients = users.map(user=>user.email).join(',');
// 'john@something.com','jane@something.com'

Now you have all the recipients. Next use the nodemailer example to send emails to all the recipient at once

Suraj Sharma
  • 777
  • 6
  • 10
0

Your code will work. But if you want to send the same email to many recipients, there is an easier way to do this.

As you can see in the nodemailer documentation, the field to is a comma-separated list or an array of recipients email addresses that will appear on the To: field. So something like this will do the job

const userEmails = users.map(item => item.email); // array of user email
const mailOptions = { // send the same email to many users
    from: '*****@gmail.com',
    to: userEmails, 
    subject: subject, // Any subject
    text: message // Any message
}

transporter.sendMail(mailOptions, (err, info) => {
   if (err) {
      console.log(err)
   } else {
      console.log(info)   
   }
})
Đăng Khoa Đinh
  • 5,038
  • 3
  • 15
  • 33