在我的 Node Express 服务器中注册用户后,我想发送一封验证电子邮件。如果创建了用户,我使用此功能发送电子邮件:
import dotenv from 'dotenv'
import sgMail from '@sendgrid/mail'
sgMail.setApiKey(process.env.SENDGRID_API_KEY)
const sendEmail = (to, token) => {
const msg = {
to,
from: process.env.SENDGRID_SENDER,
subject: 'Email Verification',
text: `Please click the following link: http://localhost:5000/${token}`
}
sgMail
.send(msg)
.then((response) => {
console.log(response[0].statusCode)
console.log(response[0].headers)
})
.catch((error) => {
console.error(error)
})
}
export { sendEmail }
这里叫:
const registerUser = asyncHandler(async (req, res) => {
const { name, email, password } = req.body
const userExists = await User.findOne({ email })
if (userExists) {
res.status(400)
throw new Error('User already exists')
}
const user = await User.create({
name,
email,
password
})
if (user) {
sendEmail(user.email, user.token) //HERE
res.status(201).json({
_id: user._id,
name: user.name,
email: user.email,
isAdmin: user.isAdmin,
isVerified: user.isVerified,
token: generateToken(user._id),
})
} else {
res.status(400)
throw new Error('Invalid user data')
}
})
我遇到的问题是,当发出请求时,我收到 ResponseError Unauthorized(代码 401)。用户确实在系统中创建。在我的 sendgrid 帐户上,我已验证具有完全访问权限的发件人电子邮件,并将我的 API 密钥存储在我的 .env 文件中。
我用了 10 分钟的邮件帐户来测试这个帐户和真实的电子邮件帐户。
如果 401 状态来自 sendgrid 那么可能你的 env 变量未解析。 导入
dotenv
包后尝试此行
dotenv.config()
如果它不起作用,请在使用它之前尝试控制台记录
process.env.SENDGRID_API_KEY
以确保它在那里。
我也有同样的问题。这是误导性的,因为它们的 SENDGRID_API_KEY 与较小字符串的命名法相匹配。我认为更长的那一个就是秘密。使用较长的字符串作为密钥。那对我有用。
从 '@sendgrid/mail' 导入 sgMail 并设置你的 api 密钥 sgMail.setApiKey('your api key is here')
https://app.sendgrid.com/guide/integrate/langs/nodejs
require('dotenv').config();
const sgMail = require('@sendgrid/mail')
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: '[email protected]', // Change to your recipient
from: '[email protected]', // Change to your verified sender
subject: 'Sending with 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('Email sent')
})
.catch((error) => {
console.error(error)
})