将表单数据邮寄到我的收件箱的应用程序在Firebase上无法正常运行

问题描述 投票:9回答:2

我想我在这里错过了很简单的东西。我有一个简单的单页node.js应用程序,它使用nodemailer将任何表单数据通过电子邮件发送到我的收件箱。

我的index.js文件:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

var transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: '[email protected]',
        pass: 'mypassword'
    }
});

app.use(express.static('public')); //public folder with my html files
app.get('', function (req, res) {
    res.sendFile(__dirname + "/");
})

app.post('/', function (req, res) {
    response = {
        name: req.body.name,
        email: req.body.email,
        message: req.body.message
    };
    var mailClient = {
        from: '[email protected]',
        to: '[email protected]',
        subject: `Message from ${response.name}`,
        text: 'MyMessage'
    };
    transporter.sendMail(mailClient, function (error, info) {
        if (error) {
            console.log(error); //not happening
        } else {
            res.redirect("/success.html"); //also not happening
        }
    });
})

var server = app.listen(80, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("App listening at http://%s:%s", host, port)
})

当我在我的本地机器上使用npm start在根目录中运行它时,该应用程序在localhost上运行完全正常。 Nodemailer正常工作;当我提交时,我的表单数据会通过电子邮件发送给我自己,然后我会被重定向到我的成功页面。

但是,当我将其部署到Firebase时,似乎nodemailer部分不起作用。页面加载我的静态文件,但当我尝试通过表单提交任何内容时,页面只是刷新(就像你有一个带有HTML的提交按钮),而不是重定向到我的成功页面和电子邮件数据。

我的代码中是否需要更改以使其与firebase一起使用?

编辑 - 没有日志:enter image description here

node.js firebase google-cloud-functions nodemailer
2个回答
3
投票

Google需要付费帐户才能使用“出站网络”。免费套餐不允许您拨打外拨电话。这包括将邮件发送到远程邮件服务器(例如向Yahoo,Gmail或Outlook帐户发送电子邮件)。

See their pricing page for more info.

寻找“出站网络”。

如果你想利用Gmail的API,你仍然可以使用nodemailer和firebase功能,实现你想要的并保留在Free Tier上。 A fully working example is already available in the firebase-samples repository!我想强调链接教程提到的内容,即Gmail确实有一个你应该注意的email sending quota


1
投票

我试图找出你的代码中的问题,但没有找到任何问题,我也有功能发送带有验证码验证/验证电子邮件ID的电子邮件。为此,我创建了一个gmail id并提供了用于发送邮件的id /密码。当用户注册是电子邮件ID时,我们使用node.js从该gmail id发送邮件,我们发送带有veirfication代码的电子邮件。我的代码如下:

'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
var bodyParser = require('body-parser');
var users = require('./users/route');

const app = express();
const nodemailer = require('nodemailer');
// Configure the email transport using the default SMTP transport and a GMail account.
// For other types of transports such as Sendgrid see https://nodemailer.com/transports/
// TODO: Configure the `gmail.email` and `gmail.password` Google Cloud environment variables.
const gmailEmail = '[email protected]';
const gmailPassword = 'password';
const gcm = require('node-gcm');
const mailTransport = nodemailer.createTransport(
        `smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`);

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}))

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "https://myapp.firebaseio.com"
});
//admin.initializeApp(functions.config().firebase);

// Express middleware that validates Firebase ID Tokens passed in the Authorization HTTP header.
// The Firebase ID token needs to be passed as a Bearer token in the Authorization HTTP header like this:
// `Authorization: Bearer <Firebase ID Token>`.
// when decoded successfully, the ID Token content will be added as `req.user`.
const authenticate = (req, res, next) => {
    if (!req.headers.authorization || !req.headers.authorization.startsWith('Bearer')) {
        res.status(403).send('Unauthorized');
        return;
    }
    const idToken = req.headers.authorization.split('Bearer ')[1];
    admin.auth().verifyIdToken(idToken).then(decodedIdToken => {
        req.user = decodedIdToken;
        next();
    }).catch(error => {
        res.status(403).send('Unauthorized');
    });
};

app.get("/token", (req, res) => {

    res.status(200).send(admin.auth().applicationDefault());
    admin.auth().createCustomToken(req.query.uid)
            .then(function (customToken) {
                res.status(200).send(customToken);
            })
            .catch(function (error) {
                console.log("Error creating custom token:", error);
            });

});


// GET /api/verifyEmail?code="1234"
app.get('/verifyEmail', (req, res) => {

    // Get the one-time code from the query parameter.
    var verificationCode = req.query.code;
    var displayName = req.query.displayName;
    var email = req.query.email; //If GET request
    const mailOptions = {
        from: `Linkuni <[email protected]>`,
        to: email
    };

    // The user subscribed to the newsletter.
    mailOptions.subject = `Welcome to Linkuni`;
    mailOptions.text = `Hi ${displayName || ''}\n\n Welcome to Linkuni. We hope you will enjoy our service. Please enter this code:${verificationCode} into the app.\n\nThank you,\nLinkuni Team`;

    return mailTransport.sendMail(mailOptions).then(() => {
        console.log('Verification email sent to:', email);
    });
});

希望这可以帮助!! :)

© www.soinside.com 2019 - 2024. All rights reserved.