Npm sendgrid mail

To send emails using SendGrid with npm, you can use the sendgrid package. Here's a step-by-step guide:

Install the sendgrid package

Run the following command in your terminal:

npm install sendgrid

Import the sendgrid package

In your JavaScript file, import the sendgrid package:

const sgMail = require('@sendgrid/mail');

Set your SendGrid API key

Set your SendGrid API key as an environment variable or as a variable in your code:

sgMail.setApiKey(process.env.SENDGRID_API_KEY);

Create a SendGrid email object

Create a new email object using the sendgrid package:

const msg = {
  to: '[email protected]',
  from: '[email protected]',
  subject: 'Hello from SendGrid!',
  text: 'Hello from SendGrid!',
  html: '<strong>Hello from SendGrid!</strong>'
};

Send the email

Use the send method to send the email:

sgMail.send(msg);

Example code

Here's the complete example code:

const sgMail = require('@sendgrid/mail');

sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const msg = {
  to: '[email protected]',
  from: '[email protected]',
  subject: 'Hello from SendGrid!',
  text: 'Hello from SendGrid!',
  html: '<strong>Hello from SendGrid!</strong>'
};

sgMail.send(msg);

Error handling

You can also handle errors using the catch block:

sgMail.send(msg)
 .then(() => console.log('Email sent!'))
 .catch((error) => console.error('Error sending email:', error));

That's it! With these steps, you should be able to send emails using SendGrid with npm.