📅  最后修改于: 2023-12-03 15:34:56.227000             🧑  作者: Mango
SendGrid SDK for Node.js is a powerful Node.js module that provides easy integration with SendGrid's email delivery service. With just a few lines of code, you can easily configure and send emails through SendGrid with Node.js.
You can install SendGrid SDK for Node.js using npm:
npm install @sendgrid/mail
To use SendGrid SDK for Node.js, you must first configure your SendGrid API key. You can obtain your API key from the SendGrid website.
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
Once your API key is set, you can use SendGrid SDK for Node.js to send emails:
const msg = {
to: 'test@example.com',
from: 'test@example.com',
subject: 'Test Email',
text: 'Hello World!',
html: '<p>Hello World!</p>',
};
sgMail
.send(msg)
.then(() => console.log('Email sent'))
.catch((error) => console.error(error));
You can also add attachments to your emails. You can attach a file from your local filesystem or provide a URL to the file:
const msg = {
to: 'test@example.com',
from: 'test@example.com',
subject: 'Test Email with Attachment',
text: 'Hello World!',
attachments: [
{
content: 'Hello World!',
filename: 'hello_world.txt',
type: 'text/plain',
disposition: 'attachment',
},
{
path: '/path/to/file.txt',
},
{
path: 'http://example.com/image.png',
},
],
};
sgMail
.send(msg)
.then(() => console.log('Email sent'))
.catch((error) => console.error(error));
SendGrid SDK for Node.js provides an easy and powerful way to send emails through SendGrid's email delivery service. With the ability to configure and send emails with just a few lines of code, it is a powerful tool for any Node.js developer.