How to send mail to multiple user using Nodemailer And Firebase asynchronously

Viewed 633

I ve tried different loop function to send mail from my cloud database. the code below sends the mail but I can't send mail that contain details specific to each recipiant

I want to loop through my database collection and send mails asynchronously.

const functions = require('firebase-functions');
const nodemailer = require('nodemailer');

////we would use receipt for the testing of the loop

//google account credentials used to send email
var transporter = nodemailer.createTransport({
    host: "smtp.example.com",
    port: 587,
    secure: true,
    auth: {
        user: '***********@fastfood.com',
        pass: '********'
    }
});
exports.newsletters = functions.firestore
.document('Puns/{orderId}')
.onWrite((snap, context)=> {
     var Emails = ['Cyrilogoh@gmail.com', 'mariajame34@gmail.com','therealogoh@gmail.com','faraway@gmail.com']
const mailOptions = {
    from: `cyrilogoh@gmail.com`,
    to: Emails,
    subject: `test`,
    html: `<h1>test</h1>
                        <p>
                          Array Works 
                        </p>`                              

};
return transporter.sendMail(mailOptions, (error, data) => {
    if (error) {
        console.log(error)
        return
    }
    console.log("Sent!")
});
});```
1 Answers

In this case you can get the data from your recently added document on the snapshot object being passed to your onWrite call.

Without more details on your firestore structure and what kind of data you getting, here is a snippet that can help you start building your async email call:

//google account credentials used to send email
var transporter = nodemailer.createTransport({
    host: "smtp.example.com",
    port: 587,
    secure: true,
    auth: {
        user: '***********@fastfood.com',
        pass: '********'
    }
});

exports.newsletters = functions.firestore.document('Puns/{orderId}').onWrite((snapshot, context)=> {

    var document = snapshot.data();

    //data to be added on the email body (could be anything)
    var data = document.body

    const mailOptions = {
        from: `cyrilogoh@gmail.com`,
        to: document.email,
        subject: `test`,
        //add whatever data you want here
        html: data
    };
    return transporter.sendMail(mailOptions, (error, data) => {
        if (error) {
            console.log(error)
            return
        }
        console.log("Sent!")
    });
})

You can get user specific data inside the document object to check which user should receive each email, assuming the collection has that data or reference to a userId to be searched on a different collection.

Hope This helps.

Related