1

Send e-mail, via e-mail addresses stored in firebase send emails altomatically on commemorative dates. example birthday and christmas. What is the best way to do this? Thank you!

1 Answers1

0

You may do this with one cron-job & HTTPS Function. For example everyday morning, this cronjob will fire a HTTPS function and this function will filter users who have a birthday the day. You may fire the HTTPS functions with below line at cronjob:

https://us-central1-[your-project-id].cloudfunctions.net/sendBirthdayMessage

And at index.js

const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
const asyncLoop = require('node-async-loop');
const dB = admin.database();

exports.sendBirthdayMessage = functions.https.onRequest((req, res) => {
    var d= new Date();
    var day = d.getDate();
    var mo = d.getMonth();

    // At this moment, I could not find more elegant way to retrive user who has birthday same with the recent  month and day. So you may implement this later on.
    // Assume you have user birthday has  day and month seperately defined.
    // Assuming user object has child with `birthMonth` users bd month.

    var ref = dB.ref('users').orderByChild('birthMonth').equalTo(mo);
    var birthdayUsers=[]; 
    ref.once('value', snp =>{ 
        if (snp.exists()) {
           snp.forEach((u,inx)=>{
              if (u.birthDay==day) {
                  birthdayUsers.push(u.val());
              }
              if (inx==snp.length-1) {
                  sendBirthdayMessage(birthdayUsers);
              }
           })

        }
    })
   res.send("Birtday message sent !");
})

function sendBirthdayMessage(users) {

 asyncLoop(users, function (item, next) {                                                       
        const email = item.mail;
        const mailOptions = {
          from: `${APP_NAME} <mail@your-sender-domain.com>`,
          to: email
        };

       mailOptions.subject = 'Happy Birthday';
       mailOptions.html = 'Hey '+ item.name + ' !' + '<br /><br /> Happy Birtday bla bla bla..'+  '<br /><br />'; 

      mailTransport.sendMail(mailOptions).then(() => {
        dB.ref('users/'+item.uid+'/bdstaut').set('bd message sent');
            console.log('Bd message sent', email);
        }).catch(error => {
            dB.ref('users/'+item.uid+'/bdstaut').set('error');
            console.error('Error:', email, error);  
        });
    setTimeout(()=>{
         next();
     },105)
    });
}

Honestly, above code may contain the syntax error. But I am sure it will work. if you meet any error just console the values at that levels.

Cappittall
  • 3,300
  • 3
  • 15
  • 23