Skip to content

Instantly share code, notes, and snippets.

@philnash
Created February 5, 2021 06:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philnash/08d3c6ab39c0bd15e394fd41a6b3db50 to your computer and use it in GitHub Desktop.
Save philnash/08d3c6ab39c0bd15e394fd41a6b3db50 to your computer and use it in GitHub Desktop.
Send an email with SendGrid in Node.js

Send an email with SendGrid in Node.js

This is an example of how to send an email. To run this script you should:

  1. Download the index.js and package.json files
  2. Install the dependencies with npm install
  3. Get a SendGrid API key from your SendGrid dashboard
  4. Verify an email address or authenticate a domain so that you can send emails with SendGrid
  5. Set the credentials and other variables in the environment and run the script:
SENDGRID_API_KEY=xyz789 \
  FROM_EMAIL=my_verified_email@domain.com \
  TO_EMAIL=myemail@provider.com \
  node index.js

Alternatively, you can replace the calls to process.env with your variables.

Run the script and you will receive an email.

const sendgrid = require("@sendgrid/mail");
sendgrid.setApiKey(process.env.SENDGRID_API_KEY);
function sendEmail(from, to, subject, body) {
sendgrid
.send({ from, to, subject, text: body })
.then(() => {
console.log(`Email sent from ${from} to ${to}`);
})
.catch((error) => {
console.error(error);
});
}
sendEmail(
process.env.FROM_EMAIL,
process.env.TO_EMAIL,
"Email notification!",
"This is an email notification!"
);
{
"name": "email",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "Phil Nash <philnash@twilio.com> (https://philna.sh)",
"license": "MIT",
"dependencies": {
"@sendgrid/mail": "^7.4.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment