Firebase功能nodemailer:gmail和oauth2在免费计划上失败

时间:2018-04-16 09:46:44

标签: firebase oauth-2.0 google-cloud-functions gmail-api nodemailer

我正在使用带有nodemailer的Firebase功能从我网站上的联系表单发送电子邮件。

我正处于免费计划中,据我所知,Gmail API被认为是Google服务而不是一般的互联网请求,因此它应该可以正常使用。

这是我的Typescript代码

import * as functions from 'firebase-functions';
import * as nodemailer from 'nodemailer';
import { DocumentSnapshot } from 'firebase-functions/lib/providers/firestore';

export const sendMessage = functions.firestore.document('/emails/{pushKey}').onCreate((snap: DocumentSnapshot) => {

  const form = snap.data();

  const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      type: 'OAuth2',
      user: 'myemail@gmail.com',
      clientId: 'xxxxxxxxxxxxx',
      clientSecret: 'xxxxxxxxx',
      refreshToken: 'xxxxxxxxx'
    },
    debug: true
  });

  const mailOptions = {
    from: 'sender@gmail.com',
    to: 'receiver@gmail.com',
    subject: `Message from ${form.name} <${form.email}>`,
    html: form.message
  };

  return transporter.sendMail(mailOptions)
    .then(() => {
      console.log('Email sent.');
    }).catch((err) => {
      console.log(err);
    });
});

但是,我进入了控制台日志

  • sendMessage 功能执行耗时2908毫秒,状态结束:'ok'

  • sendMessage 函数返回未定义,预期的承诺或值

  • sendMessage 未配置结算帐户。外部网络无法访问,配额严重受限。配置结算帐户以删除这些限制

  • sendMessage 功能执行已开始

我在这里使用任何外部网络了吗?

以下代码适用

import * as functions from 'firebase-functions';
import * as nodemailer from 'nodemailer';
import { DocumentSnapshot } from 'firebase-functions/lib/providers/firestore';


const gmailEmail = encodeURIComponent(functions.config().gmail.email);
const gmailPassword = encodeURIComponent(functions.config().gmail.password);
const mailTransport = nodemailer.createTransport(`smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`);

export const sendMessage = functions.firestore.document('/emails/{pushKey}').onCreate((snap: DocumentSnapshot) => {

  const form = snap.data();

  const mailOptions = {
    to: 'receiver@gmail.com',
    subject: `Message from ${form.name} <${form.email}>`,
    html: form.message
  };
  return mailTransport.sendMail(mailOptions)
    .then(() => console.log('worked!'))
    .catch(e => console.log(e));
});

但这种方式是不安全的,它要求我允许在我的Gmail帐户上安全性较低的应用。

如何将Gmail和OAuth2与免费的Firebase计划一起使用?

1 个答案:

答案 0 :(得分:-2)

因此,您无法在Firebase免费计划上发出出站请求。您需要升级您的计划以进行出站请求,我相信,因为您使用的是“nodemailer”,它是尝试发出出站请求的部分。以下是关于升级使用邮件服务的评论的另一个问题:How can I use nodemailer with Cloud Functions for Firebase?

我相信Firebase也会让Blaze计划免费,直到您超过免费计划的配额,所以在您超过定价(https://firebase.google.com/pricing/)中指定的免费配额之前,它确实不会花费任何费用。

相关问题