To send an email using SendGrid in Node.js, you will need to install the SendGrid Node.js library and then use its send
method to send an email. Here’s an example of how you could do this:
1. First, install the SendGrid library using npm:
npm install @sendgrid/mail
2. Next, require the @sendgrid/mail
module in your Node.js script:
const sgMail = require('@sendgrid/mail');
3. Set your SendGrid API key as an environment variable or in your Node.js script:
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
4. Use the send
method to send an email:
const msg = {
to: '[email protected]',
from: '[email protected]',
subject: 'Hello World',
text: 'Hello, World!',
html: '<p>Hello, World!</p>',
};
sgMail.send(msg);
This will send an email with the subject “Hello World” and the body “Hello, World!” to the recipient’s email address.
You can also include additional options in the message object, such as cc
, bcc
, and attachments
, to specify the email’s carbon copy recipients, blind carbon copy recipients, and attachments, respectively.
For more information on the options available in the message object and the send
method, you can refer to the SendGrid documentation.