How to send emails with SendGrid in Node.js
Using a dedicated email service like SendGrid provides better deliverability, analytics, and scalability compared to traditional SMTP servers.
As the creator of CoreUI, a widely used open-source UI library, I’ve integrated SendGrid into enterprise Node.js applications throughout my 11 years of backend development.
The most efficient approach is using the official @sendgrid/mail package with an API key for authentication.
This method offers reliable email delivery with built-in retry logic and detailed sending statistics.
Use the @sendgrid/mail package with an API key to send emails through SendGrid.
const sgMail = require('@sendgrid/mail')
sgMail.setApiKey(process.env.SENDGRID_API_KEY)
const msg = {
to: '[email protected]',
from: '[email protected]',
subject: 'Welcome to Our Service',
text: 'Thank you for signing up!',
html: '<strong>Thank you for signing up!</strong>'
}
sgMail.send(msg)
.then(() => {
console.log('Email sent successfully')
})
.catch((error) => {
console.error('Error sending email:', error)
})
Here the SendGrid API key is set using setApiKey from an environment variable. The message object contains recipient, sender, subject, and both plain text and HTML versions of the content. The send method returns a Promise that resolves when the email is successfully queued for delivery or rejects with an error.
Best Practice Note:
This is the same approach we use in CoreUI enterprise applications for transactional emails at scale. Always verify your sender domain with SendGrid for better deliverability, use environment variables for API keys, and implement proper error handling to retry failed sends or log them for manual review.



