Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
166
rated 0 times [  170] [ 4]  / answers: 1 / hits: 5738  / 3 Years ago, thu, april 8, 2021, 12:00:00

After registering a user in my node express server, I would like to send a verification email. If the user is created I use this function to send the email:


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 }

It is called here:


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')
}
})

The problem I am having is I get a ResponseError Unauthorized (code 401) when the request is made. The user does get created in the system. On my sendgrid account, I have verified the sender email with full access and I am storing my API Key in my .env file.


I have used 10 minute mail accounts to test this and real email accounts.


More From » node.js

 Answers
17

If the 401 status is coming from sendgrid then probably your env variable is not resolved.
try this line after you import the dotenv package


dotenv.config()

If it didn't work, try to console.log the process.env.SENDGRID_API_KEY before u use it to make sure it's there.


[#1504] Sunday, April 4, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jackelyn

Total Points: 303
Total Questions: 103
Total Answers: 102

Location: Turks and Caicos Islands
Member since Sun, Mar 7, 2021
3 Years ago
jackelyn questions
Sun, Feb 28, 21, 00:00, 3 Years ago
Mon, May 25, 20, 00:00, 4 Years ago
Thu, Apr 30, 20, 00:00, 4 Years ago
Fri, Mar 27, 20, 00:00, 4 Years ago
;