如何将节点管理器与Firebase的云功能一起使用?

时间:2017-04-09 11:46:46

标签: firebase google-cloud-functions nodemailer firebase-cloud-functions

我正在尝试在nodemailer中使用Cloud Functions for Firebase,但不断收到错误,似乎无法访问或找到smpt服务器。我试过gmail,outlook和一个普通的托管服务。它适用于我的本地节点服务器。

这是我尝试发送电子邮件失败时收到的记录错误:

{
  Error: getaddrinfoENOTFOUNDsmtp-mail.outlook.comsmtp-mail.outlook.com: 587aterrnoException(dns.js: 28: 10)atGetAddrInfoReqWrap.onlookup[
    asoncomplete
  ](dns.js: 76: 26)code: 'ECONNECTION',
  errno: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'smtp-mail.outlook.com',
  host: 'smtp-mail.outlook.com',
  port: '587',
  command: 'CONN'
}

1 个答案:

答案 0 :(得分:2)

我创建了一个云功能(http事件),通过以下方式从我网站的联系表单部分发送电子邮件:

const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
const rp = require('request-promise');

//google account credentials used to send email
const mailTransport = nodemailer.createTransport(
    `smtps://user@domain.com:password@smtp.gmail.com`);

exports.sendEmailCF = functions.https.onRequest((req, res) => {

  //recaptcha validation
  rp({
        uri: 'https://recaptcha.google.com/recaptcha/api/siteverify',
        method: 'POST',
        formData: {
            secret: 'your_secret_key',
            response: req.body['g-recaptcha-response']
        },
        json: true
    }).then(result => {
        if (result.success) {
            sendEmail('recipient@gmail.com', req.body).then(()=> { 
              res.status(200).send(true);
            });
        }
        else {
            res.status(500).send("Recaptcha failed.")
        }
    }).catch(reason => {
        res.status(500).send("Recaptcha req failed.")
    })

});

// Send email function
function sendEmail(email, body) {
  const mailOptions = {
    from: `<noreply@domain.com>`,
    to: email
  };
  // hmtl message constructions
  mailOptions.subject = 'contact form message';
  mailOptions.html = `<p><b>Name: </b>${body.rsName}</p>
                      <p><b>Email: </b>${body.rsEmail}</p>
                      <p><b>Subject: </b>${body.rsSubject}</p>
                      <p><b>Message: </b>${body.rsMessage}</p>`;
  return mailTransport.sendMail(mailOptions);
}