首页 > 解决方案 > Nodemailer 自定义 SMTP 不适用于 Firebase 功能

问题描述

我有一个错误。我正在使用 nodemailer 从我的 Firebase 应用程序发送电子邮件。

这是我的代码的样子:

const functions = require('firebase-functions');
const admin = require("firebase-admin");
const nodemailer = require('nodemailer');

admin.initializeApp();

//THESE SETTINGS WORK ON LOCAL AND LIVE. BUT I DONT WANT TO USE THEM
// const transporter = nodemailer.createTransport({
//     service: 'gmail',
//     auth: {
//         user: 'GMAIL HERE',
//         pass:  'GMAIL PW HERE'
//     },
// })

//THESE SETTINGS WORK ON LOCAL, BUT NOT ON LIVE.
const transporter = nodemailer.createTransport({
    host: "smtp.mycompanyname.com",
    port: 25,
    secureConnection: false, // TLS requires secureConnection to be false
    logger: true,
    debug: true,
    secure: false,
    requireTLS: true,
    auth: {
        user: "USERNAME HERE",
        pass: "PASSWORD HERE"
    },
    tls: { rejectUnauthorized: false }
})

exports.sendConfirmationEmail = functions.https.onCall((data, context) => {

    var email_adress        = data.data.email;

    var email = {
        from: 'E-Mail Adress Goes Here',
        to: email_adress,
        subject: 'BlaBlaBla',
        text: 'BlaBlaBla',
        html: 'BlaBlaBla'
    };
    // Function to send e-mail to the user
    transporter.sendMail(email, function(err, info) {
        if (err) {
            console.log(err);
            return { success: false };
        } else {
            return { success: true }
        }
    });

})

现在。如果我使用 GMail 设置。一切正常。它发送电子邮件。但是,我公司有自己的 SMTP 服务器。SMTP 适用于 Firebase 身份验证电子邮件。它正在成功发送这些电子邮件。

当我将上述配置粘贴到本地环境中时,SMTP 服务器也可以工作。但是,当我在 Firebase Cloud 函数中运行它时,会出现以下错误:

10:24:43.479 AM
sendConfirmationEmail
[2020-09-25 08:24:43] DEBUG [Cq6p67HnXLA] Closing connection to the server using "destroy"
10:24:43.479 AM
sendConfirmationEmail
[2020-09-25 08:24:43] ERROR Send Error: Connection timeout
10:24:44.673 AM
sendConfirmationEmail
{ Error: Connection timeout
10:24:44.673 AM
sendConfirmationEmail
    at SMTPConnection._formatError (/workspace/node_modules/nodemailer/lib/smtp-connection/index.js:784:19) 
10:24:44.674 AM
sendConfirmationEmail
    at SMTPConnection._onError (/workspace/node_modules/nodemailer/lib/smtp-connection/index.js:770:20) 
10:24:44.674 AM
sendConfirmationEmail
at Timeout._connectionTimeout.setTimeout (/workspace/node_modules/nodemailer/lib/smtp-connection/index.js:235:22)

我尝试过使用不同的 nodemailer 选项,但到目前为止还没有取得很大的成功。这也使得它在本地很难工作,但是当我部署它时却没有。

有任何想法吗?

标签: javascriptnode.jsfirebasegoogle-cloud-functionsnodemailer

解决方案


我遇到了完全相同的问题,并且需要一些挖掘,但解决方案非常简单。

解决方案


不能在 Cloud Function的端口 25上使用出站连接。


所以我将端口更改为 465 并使用安全连接,它确实有效。

我(随机)在提示和技巧文档页面上发现了这一点。

PS:同样的限制也适用于 Compute Engine(请参阅docs)。


推荐阅读