我正在尝试在我的Heroku NodeJS应用程序中设置SendGrid附加组件,我创建了API Key并将其设置为环境变量。
整个API Key看起来是这样的。SG.actualValue.bbb_cccccc
我做的第一次设置,我把整个密钥设置为我的SENDGRID_API_KEY,然后我得到了这个错误。
API key does not start with SG.
所以,我意识到了这个错误,于是取消了环境变量的设置,并再次将其设置为整个键的 actualValue 部分。
然而,我还是得到了同样的错误。我试着再次做同样的事情,或者重启终端(实际上是整个笔记本)。
这是我试图从SendGrid设置页面运行的测试代码。
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY)
const msg = {
to: '[email protected]',
from: '[email protected]',
subject: 'Sending with Twilio SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sgMail.send(msg);
我试着创建一个新的键并设置它,但我得到了同样的错误。我试着把它设置为整个键,但是没有".SG "或者只有bbb_ccccc部分。 先谢谢你。
...的API key不以SG开头。
意味着SendGrid的API Key SHOULD 起于 SG.
所以你没有正确设置环境变量。你需要检查一下。只要用 console.log
打印环境变量。或者,使用
$ heroku run bash -a mighty-river-12802
为您的应用程序启动一个控制台,并使用 printenv
打印环境变量。
Running bash on ⬢ mighty-river-12802... up, run.1571 (Free)
~ $ printenv
TERM=xterm-256color
WEB_MEMORY=512
MEMORY_AVAILABLE=512
COLUMNS=367
DYNO=run.1571
PATH=/app/.heroku/node/bin:/app/.heroku/yarn/bin:/usr/local/bin:/usr/bin:/bin:/app/bin:/app/node_modules/.bin
WEB_CONCURRENCY=1
_=/usr/bin/printenv
PWD=/app
PS1=\[\033[01;34m\]\w\[\033[00m\] \[\033[01;32m\]$ \[\033[00m\]
NODE_ENV=production
LINES=49
TIMES=5
HOME=/app
SHLVL=2
PORT=6791
NODE_HOME=/app/.heroku/node
TIMES: 5
环境变量是通过heroku配置变量来设置的。
例如:
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: '[email protected]',
from: '[email protected]',
subject: 'Sending with Twilio SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sgMail
.send(msg)
.then(() => console.log('send mail success'))
.catch(console.log);
$ export SENDGRID_API_KEY=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
$ node index.js
send mail success
如期收到邮件。
hello there 如果你使用node js,请确保你在需要sendgridnodemailer模块的文件里有require('dotenv').config()。如果没有它,sendgrid transporter会有一个未定义的值,而不是api_key.我也遇到了同样的问题,它解决了。