【问题标题】:Send emails altomaticamente, from email addresses stored in the firebase [duplicate]从存储在 Firebase 中的电子邮件地址发送电子邮件 altomaticamente [重复]
【发布时间】:2023-03-12 07:35:01
【问题描述】:

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

【问题讨论】:

    标签: email firebase


    【解决方案1】:

    您可以使用一个 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)
        });
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-18
      • 2016-11-04
      • 1970-01-01
      • 2019-11-25
      • 1970-01-01
      • 2014-07-20
      • 1970-01-01
      • 2017-03-01
      相关资源
      最近更新 更多