【问题标题】:How to send email in Firebase for free?如何在 Firebase 中免费发送电子邮件?
【发布时间】:2020-03-15 00:07:27
【问题描述】:

我知道 Firebase 不允许您使用第 3 方电子邮件服务发送电子邮件。所以唯一的方法是通过 Gmail 发送。

所以我在互联网上搜索了方法,所以这里有一个 sn-p,它可以让我免费发送电子邮件。

export const shareSpeechWithEmail = functions.firestore
  .document("/sharedSpeeches/{userId}")
  .onCreate(async (snapshot, context) => {
    // const userId = context.params.userId;
    // const data = snapshot.data();
    const mailTransport = nodemailer.createTransport(
      `smtps://${process.env.USER_EMAIL}:${process.env.USER_PASSWORD}@smtp.gmail.com`
    );


    const mailOptions = {
      to: "test@gmail.com",
      subject: `Message test`,
      html: `<p><b>test</b></p>`
    };
    try {
      return mailTransport.sendMail(mailOptions);
    } catch (err) {
      console.log(err);
      return Promise.reject(err);
    }
  });

我想创建一个模板,所以我将这个名为email-templates 的包用于nodemailer。 但该函数不会在 Firebase 控制台中执行,也不会显示错误并显示与“计费”相关的警告。

export const shareSpeechWithEmail = functions.firestore
  .document("/sharedSpeeches/{userId}")
  .onCreate(async (snapshot, context) => {

    const email = new Email({
      send: true,
      preview: false,
      views: {
        root: path.resolve(__dirname, "../../src/emails")
        // root: path.resolve(__dirname, "emails")
      },
      message: {
        // from: "<noreply@domain.com>"
        from: process.env.USER_EMAIL
      },
      transport: {
        secure: false,
        host: "smtp.gmail.com",
        port: 465,
        auth: {
          user: process.env.USER_EMAIL,
          pass: process.env.USER_PASSWORD
        }
      }
    });

    try {
      return email.send({
        template: "sharedSpeech",
        message: {
          to: "test@gmail.com",
          subject: "message test"
        },
        locals: {
          toUser: "testuser1",
          fromUser: "testuser2",
          title: "Speech 1",
          body: "<p>test using email <b>templates</b></p>"
        }
      });
    } catch (err) {
      console.log(err);
      return Promise.reject(err);
    }
  });

【问题讨论】:

    标签: node.js firebase google-cloud-functions


    【解决方案1】:

    只要您的项目在 Blaze 计划中,您绝对可以使用第三方服务和 Cloud Functions 发送电子邮件。官方提供的示例甚至建议“如果切换到 Sendgrid、Mailjet 或 Mailgun,请确保在 Firebase 项目上启用计费,因为这是向非 Google 服务发送请求所必需的。”

    https://github.com/firebase/functions-samples/tree/master/quickstarts/email-users

    无论您使用哪种电子邮件系统,这里的关键是您确实需要升级到 Blaze 计划才能建立传出连接。

    【讨论】:

    • 假设我启用了 blaze 计划并使用 sendgrid 发送电子邮件。即使我没有达到他们免费计划中的配额,它会花费一些东西吗?
    • 如果您有计费问题,请咨询pricing guide。如果没有足够的信息,请联系 Firebase 支持以解决计费问题。 support.google.com/firebase/contact/support
    【解决方案2】:

    您可以使用 nodemailer 发送电子邮件:

    npm install nodemailer cors
    
    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    const nodemailer = require('nodemailer');
    const cors = require('cors')({origin: true});
    admin.initializeApp();
    
    /**
    * Here we're using Gmail to send 
    */
    let transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: 'yourgmailaccount@gmail.com',
            pass: 'yourgmailaccpassword'
        }
    });
    
    exports.sendMail = functions.https.onRequest((req, res) => {
        cors(req, res, () => {
    
            // getting dest email by query string
            const dest = req.query.dest;
    
            const mailOptions = {
                from: 'Your Account Name <yourgmailaccount@gmail.com>', // Something like: Jane Doe <janedoe@gmail.com>
                to: dest,
                subject: 'test', // email subject
                html: `<p style="font-size: 16px;">test it!!</p>
                    <br />
                ` // email content in HTML
            };
    
            // returning result
            return transporter.sendMail(mailOptions, (erro, info) => {
                if(erro){
                    return res.send(erro.toString());
                }
                return res.send('Sended');
            });
        });    
    });
    

    另见here

    设置安全级别以避免错误消息: 转至:https://www.google.com/settings/security/lesssecureapps 将安全性较低的应用程序的访问权限设置为启用

    参考to

    【讨论】:

    • 谢谢,我会试试这个解决方案。我可以只用 nodemailer 发送电子邮件,但是当我使用使用 nodemailer 的电子邮件模板包时它不起作用,我想知道为什么会这样?
    • 这似乎是一个安全问题。见上文。
    • 是的,我已经打开了不太安全的应用程序。但还是同样的错误
    • 错误:无效登录:534-5.7.14 534-5.7.14 发生此错误:(我被授予访问不太安全的应用程序(在Gmail中)但仍然被阻止访问
    • 这适用于应用密码。无需为不太安全的应用打开访问权限。 (转到帐户设置并创建一个应用程序密码并将该密码作为电子邮件密码)
    【解决方案3】:

    直接通过functions.https.onCall(..)调用sendMail()云函数:

    正如@Micha 提到的,不要忘记为外发电子邮件启用不太安全的应用程序:https://www.google.com/settings/security/lesssecureapps

    const functions = require('firebase-functions');
    const nodemailer = require('nodemailer');
    
    let mailTransport = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: 'supportabc@gmail.com',
            pass: '11112222'
        }
    });
    
    exports.sendMail = functions.https.onCall((data, context) => {
    
        console.log('enter exports.sendMail, data: ' + JSON.stringify(data));
    
        const recipientEmail = data['recipientEmail'];
        console.log('recipientEmail: ' + recipientEmail);
    
        const mailOptions = {
            from: 'Abc Support <Abc_Support@gmail.com>',
            to: recipientEmail,
            html:
               `<p style="font-size: 16px;">Thanks for signing up</p>
                <p style="font-size: 12px;">Stay tuned for more updates soon</p>
                <p style="font-size: 12px;">Best Regards,</p>
                <p style="font-size: 12px;">-Support Team</p>
              ` // email content in HTML
        };
    
        mailOptions.subject = 'Welcome to Abc';
    
        return mailTransport.sendMail(mailOptions).then(() => {
            console.log('email sent to:', recipientEmail);
            return new Promise(((resolve, reject) => {
           
                return resolve({
                    result: 'email sent to: ' + recipientEmail
                });
            }));
        });
    });
    

    还要感谢:Micha's post

    【讨论】:

      【解决方案4】:

      您可以使用 Firebase 扩展程序和 Sendgrid 免费发送:

      https://medium.com/firebase-developers/firebase-extension-trigger-email-5802800bb9ea

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-20
        • 2020-12-12
        • 2020-07-19
        • 2021-06-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多