首页 > 解决方案 > Nodemailer 无法识别来自环境变量的凭据

问题描述

我创建了一个用于发送电子邮件的传输,如下所示:

const nodemailer = require('nodemailer');

const transport = nodemailer.createTransport({
  host: process.env.MAIL_HOST, 
  port: parseInt(process.env.MAIL_PORT),
  auth: {
    user: process.env.MAIL_USER,
    user: process.env.MAIL_PASS
  }
});

在我的variables.env文件中包含以下变量:

MAIL_USER=def
MAIL_PASS=abc
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525

有了这个,我得到以下错误:

(node:39148) UnhandledPromiseRejectionWarning: Error: Invalid login: 535 5.7.0 Invalid login or password
[]     at SMTPConnection._formatError (/Users/JAAI/Desktop/WB Node/Learn-Node/starter-files/node_modules/nodemailer/lib/smtp-connection/index.js:555:19)
[]     at SMTPConnection._actionAUTHComplete (/Users/JAAI/Desktop/WB Node/Learn-Node/starter-files/node_modules/nodemailer/lib/smtp-connection/index.js:1244:34)
[]     at SMTPConnection.<anonymous> (/Users/JAAI/Desktop/WB Node/Learn-Node/starter-files/node_modules/nodemailer/lib/smtp-connection/index.js:338:26)
[]     at SMTPConnection._processResponse (/Users/JAAI/Desktop/WB Node/Learn-Node/starter-files/node_modules/nodemailer/lib/smtp-connection/index.js:702:20)
[]     at SMTPConnection._onData (/Users/JAAI/Desktop/WB Node/Learn-Node/starter-files/node_modules/nodemailer/lib/smtp-connection/index.js:507:14)
[]     at TLSSocket.<anonymous> (/Users/JAAI/Desktop/WB Node/Learn-Node/starter-files/node_modules/nodemailer/lib/smtp-connection/index.js:653:51)
[]     at TLSSocket.emit (events.js:210:5)
[]     at addChunk (_stream_readable.js:309:12)
[]     at readableAddChunk (_stream_readable.js:290:11)
[]     at TLSSocket.Readable.push (_stream_readable.js:224:10)
[]     at TLSWrap.onStreamRead (internal/stream_base_commons.js:182:23)
[] (node:39148) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
[] (node:39148) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我试过控制台记录变量,它们是正确的。

console.log(process.env.MAIL_HOST)           // smtp.mailtrap.io
console.log(parseInt(process.env.MAIL_PORT)) // 2525
console.log(process.env.MAIL_USER)           // def
console.log(process.env.MAIL_PASS);          // abc

作为一种解决方法,我已经尝试过这个并且它有效:

const transport = nodemailer.createTransport({
  host: "smtp.mailtrap.io",
  port: 2525,
  auth: {
    user: "def",
    pass: "abc"
  }
});

据我所知,我看不出有什么不同。这里有什么问题?谢谢

标签: node.jsenvironment-variablesnodemailer

解决方案


推荐阅读