What is @sendgrid/client?
The @sendgrid/client npm package is a JavaScript client for interacting with the SendGrid API. It allows developers to easily integrate SendGrid's email sending capabilities into their applications. The package provides a way to send emails, manage contacts, and perform other email-related tasks programmatically.
What are @sendgrid/client's main functionalities?
Sending Emails
This feature allows you to send emails using the SendGrid API. The code sample demonstrates how to send a simple text email.
const sgClient = require('@sendgrid/client');
sgClient.setApiKey(process.env.SENDGRID_API_KEY);
const request = {
method: 'POST',
url: '/v3/mail/send',
body: {
personalizations: [{
to: [{ email: 'recipient@example.com' }],
subject: 'Hello, World!'
}],
from: { email: 'sender@example.com' },
content: [{ type: 'text/plain', value: 'Hello, World!' }]
}
};
sgClient.request(request)
.then(([response, body]) => {
console.log(response.statusCode);
console.log(body);
})
.catch(error => {
console.error(error);
});
Managing Contacts
This feature allows for the management of contacts within SendGrid. The code sample shows how to add a new contact to your SendGrid account.
const sgClient = require('@sendgrid/client');
sgClient.setApiKey(process.env.SENDGRID_API_KEY);
const request = {
method: 'PUT',
url: '/v3/marketing/contacts',
body: {
contacts: [{
email: 'newcontact@example.com',
first_name: 'First',
last_name: 'Last'
}]
}
};
sgClient.request(request)
.then(([response, body]) => {
console.log(response.statusCode);
console.log(body);
})
.catch(error => {
console.error(error);
});
Other packages similar to @sendgrid/client
nodemailer
Nodemailer is a module for Node.js applications to allow easy email sending. Unlike @sendgrid/client, which is specific to the SendGrid API, Nodemailer supports multiple transport options (SMTP, SendGrid, Mailgun, etc.). This makes Nodemailer more versatile if you need to switch between email services or configure multiple services.
mailgun-js
mailgun-js is a simple Node.js module for interacting with the Mailgun API. Similar to @sendgrid/client, it allows for sending emails, managing contacts, and more, but is focused on the Mailgun service. It's a good alternative if you're using Mailgun instead of SendGrid, offering similar functionality tailored to a different email service provider.
Client for the Sendgrid API
This client library is used by the other service packages to make requests to the Sendgrid API. You can however use it independently to make custom requests to the API as well.
Usage
const sgClient = require('@sendgrid/client');
sgClient.setApiKey(process.env.SENDGRID_API_KEY);
sgClient.setDefaultHeader('User-Agent', 'Some user agent string');
sgClient.setDefaultRequest('baseUrl', 'https://api.sendgrid.com/');
Overwrite Promise implementation
You can overwrite the promise implementation you want the client to use. Defaults to the ES6 Promise
:
global.Promise = require('bluebird');