Skip to content

Instantly share code, notes, and snippets.

@philnash

philnash/README.md

Created Feb 5, 2021
Embed
What would you like to do?
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