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 !
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)
}
})