从存储在firebase中的电子邮件地址发送电子邮件altomaticamente

时间:2018-03-23 13:50:32

标签: email firebase

通过存储在firebase中的电子邮件地址发送电子邮件,在纪念日期间中等地发送电子邮件。例如生日和圣诞节。做这个的最好方式是什么?谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用一个cron-job& HTTPS功能。例如,每天早上,此cronjob将触发HTTPS功能,此功能将过滤当天生日的用户。 你可以在cronjob下面用以下行激活HTTPS函数:

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

在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)
    });
}

老实说,上面的代码可能包含语法错误。但我相信它会奏效。如果遇到任何错误,只需控制该级别的值即可。