### Run SendGrid Node.js Tests Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/docs/examples/webhooks-docker/CONTRIBUTING.md Execute tests for the SendGrid Node.js library. This requires installing Prism, starting Prism, bootstrapping dependencies with lerna, and then running the test commands. ```bash yarn prism:install yarn prism lerna bootstrap yarn test ``` -------------------------------- ### General v3 Web API Usage Example Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/README.md Demonstrates how to initialize the SendGrid client, set your API key, and make a GET request to the v3 API keys endpoint. This serves as a foundational example for interacting with the SendGrid API. ```APIDOC ## GET /v3/api_keys ### Description This endpoint retrieves a list of API keys associated with your SendGrid account. It's a common starting point for managing API key access. ### Method GET ### Endpoint /v3/api_keys ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const client = require('@sendgrid/client'); client.setApiKey(process.env.SENDGRID_API_KEY); const request = { method: 'GET', url: '/v3/api_keys' }; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(body); }); ``` ### Response #### Success Response (200) - **api_key** (object) - An object containing API key details. #### Response Example ```json { "api_keys": [ { "id": "YOUR_API_KEY_ID", "name": "My Key Name", "last_used": "2023-10-27T10:00:00Z", "permissions": [ "mail.send" ] } ] } ``` ``` -------------------------------- ### Install and Run SendGrid Node.js Locally Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/docs/examples/webhooks-docker/CONTRIBUTING.md Follow these steps to clone the repository, install dependencies, and set up the project for local development. Requires Node.js versions 6, 8, or >=10. ```bash git clone https://github.com/sendgrid/sendgrid-nodejs.git cd sendgrid-nodejs npm install ``` -------------------------------- ### Configure SendGrid API Key Environment Variable Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/docs/examples/webhooks-docker/CONTRIBUTING.md Set up the SENDGRID_API_KEY environment variable for using SendGrid examples. This involves creating a sendgrid.env file, adding it to .gitignore, and sourcing the file. ```bash echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env echo "sendgrid.env" >> .gitignore source ./sendgrid.env ``` -------------------------------- ### Install Package Dependencies in Monorepo Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/docs/examples/webhooks-docker/CONTRIBUTING.md Install dependencies for a specific package within the sendgrid-nodejs monorepo. Navigate to the desired package directory and run either npm install or yarn install. ```bash cd packages/{NAME} npm install or yarn install ``` -------------------------------- ### Install @sendgrid/client using npm (Shell) Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/README.md Provides the command to install the @sendgrid/client package using npm. This is the recommended method for Node.js projects. Ensure npm is installed and available in your PATH. ```bash npm install --save @sendgrid/client ``` -------------------------------- ### Install @sendgrid/client using yarn (Shell) Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/README.md Provides the command to install the @sendgrid/client package using yarn. This is an alternative package manager for Node.js projects. Ensure yarn is installed and configured. ```bash yarn add @sendgrid/client ``` -------------------------------- ### Install Twilio Helper Library using npm Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/docs/use-cases/sms.md This command installs the Twilio helper library, which is necessary for interacting with the Twilio API to send SMS messages. Ensure you have Node.js and npm installed. ```bash npm install twilio ``` -------------------------------- ### Install SendGrid v2 Locally using npm Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/TROUBLESHOOTING.md This command installs a specific version of the sendgrid package locally. This is useful for projects that require a particular version for compatibility, such as continuing to use Web API v2. ```bash npm install sendgrid@1.9.2 ``` -------------------------------- ### Install a Specific SendGrid Package Version Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/TROUBLESHOOTING.md This command demonstrates how to install a specific version of a SendGrid package using npm. Replace '[package name]' with the desired package and 'X.X.X' with the version number. ```bash npm install @sendgrid/[package name]@X.X.X ``` -------------------------------- ### Attach PDF from URL with SendGrid Node.js Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/docs/use-cases/attachments.md Illustrates how to fetch a PDF from a URL, buffer its content, convert it to base64, and attach it to an email using SendGrid. This example uses the 'request' library to download the file. Ensure the 'request' library is installed and imported. ```javascript import request from 'request'; const fileURl = 'http://example.com/path/to/your/document.pdf'; // Replace with actual URL request(fileURl, { encoding: null }, (err, res, body) => { if (err) { console.error('Error fetching file:', err); return err; } if (body) { const textBuffered = Buffer.from(body); const msg = { to: 'recipient@test.org', from: 'sender@test.org', subject: 'Attachment', html: '

Here’s an attachment for you!

', attachments: [ { content: textBuffered.toString('base64'), filename: 'some-attachment.pdf', type: 'application/pdf', disposition: 'attachment', content_id: 'mytext', }, ], }; // send msg here, e.g., sgMail.send(msg); console.log('Message prepared with URL attachment:', msg); } }); ``` -------------------------------- ### Install SendGrid v2 using npm Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/TROUBLESHOOTING.md This snippet shows how to add the sendgrid v1.9.2 package to your project's dependencies in package.json and install it using npm. This is for users who need to continue using Web API v2. ```json { "dependencies": { "sendgrid": "1.9.2" } } ``` -------------------------------- ### Make Custom API Requests with SendGrid Node.js Client Source: https://context7.com/sendgrid/sendgrid-nodejs/llms.txt Access any SendGrid API endpoint directly using the `@sendgrid/client` library. This example demonstrates how to retrieve existing API keys and create a new one by making GET and POST requests to the respective endpoints. ```javascript const client = require('@sendgrid/client'); client.setApiKey(process.env.SENDGRID_API_KEY); // Get all API keys const getKeys = { method: 'GET', url: '/v3/api_keys' }; const [response, body] = await client.request(getKeys); console.log('Status:', response.statusCode); console.log('API Keys:', body.result); // Create a new API key const createKey = { method: 'POST', url: '/v3/api_keys', body: { name: 'My New API Key', scopes: ['mail.send', 'alerts.read'] } }; const [createResponse, newKey] = await client.request(createKey); console.log('Created key:', newKey.api_key_id); ``` -------------------------------- ### Install @sendgrid/inbound-mail-parser using npm Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/inbound-mail-parser/README.md Installs the @sendgrid/inbound-mail-parser package using npm, which is the recommended package manager for Node.js projects. This package is essential for consuming and processing data from the SendGrid Inbound Parse API. ```sh npm install --save @sendgrid/inbound-mail-parser ``` -------------------------------- ### GET /partner_settings Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md Retrieves a list of all available partner settings. ```APIDOC ## GET /partner_settings ### Description Retrieves a list of all available partner settings. ### Method GET ### Endpoint /v3/partner_settings ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of partner settings to return. - **offset** (integer) - Optional - The number of partner settings to skip. ### Request Example ```javascript const queryParams = { 'limit': 1, 'offset': 1 }; request.qs = queryParams; request.method = 'GET'; request.url = '/v3/partner_settings'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` ### Response #### Success Response (200) - **partner_settings** (array) - A list of partner settings objects. #### Response Example ```json { "partner_settings": [ { "name": "new_relic", "enabled": true } ] } ``` ``` -------------------------------- ### Install @sendgrid/inbound-mail-parser using yarn Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/inbound-mail-parser/README.md Installs the @sendgrid/inbound-mail-parser package using yarn, an alternative package manager for Node.js. This command adds the necessary dependency for handling SendGrid Inbound Parse API data. ```sh yarn add @sendgrid/inbound-mail-parser ``` -------------------------------- ### Retrieve All Transactional Templates (GET /templates) Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md This snippet demonstrates retrieving all transactional templates, with options to filter by 'dynamic' or 'legacy' generations, or to fetch all. It uses a GET request to the /templates endpoint. Users are limited to 300 templates. ```javascript request.method = 'GET'; request.url = '/v3/templates?generations=dynamic'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` ```javascript request.method = 'GET'; request.url = '/v3/templates?generations=legacy'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` ```javascript request.method = 'GET'; request.url = '/v3/templates?generations=legacy,dynamic'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### Set API Key and Make GET Request with SendGrid Client (Node.js) Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/README.md Demonstrates how to set the SendGrid API key and make a GET request to the '/v3/api_keys' endpoint using the @sendgrid/client package. It logs the response status code and body. Assumes SENDGRID_API_KEY is set as an environment variable. ```javascript const client = require('@sendgrid/client'); client.setApiKey(process.env.SENDGRID_API_KEY); const request = { method: 'GET', url: '/v3/api_keys' }; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(body); }) ``` -------------------------------- ### GET /tracking_settings Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md Retrieves a list of all available tracking settings. ```APIDOC ## GET /tracking_settings ### Description Retrieves a list of all tracking settings that you can enable on your account. ### Method GET ### Endpoint /v3/tracking_settings ### Parameters #### Query Parameters - **limit** (integer) - Optional - The number of results to return. - **offset** (integer) - Optional - The starting point for the results. ### Response #### Success Response (200) - **body** (object) - The response body containing the tracking settings. ### Response Example ```json { "click_tracking": { "enable": true, "enable_text": true }, "open_tracking": { "enable": true }, "subscription_tracking": { "enable": true, "substitution_tag": "<%asm_preferences_redirect_url%>" }, "ganalytics": { "enable": true, "utm_campaign": "%%x-campaign%%", "utm_content": "%%x-content%%", "utm_medium": "email", "utm_source": "sendgrid", "utm_term": "%%x-term%%" } } ``` ``` -------------------------------- ### GET /user/webhooks/event/settings Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md Retrieve your event webhook settings. ```APIDOC ## GET /user/webhooks/event/settings ### Description Retrieve your event webhook settings. ### Method GET ### Endpoint /v3/user/webhooks/event/settings ### Parameters #### Query Parameters - None #### Request Body - None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **body** (object) - Contains event webhook settings. #### Response Example ```json { "data": [ { "url": "http://example.com/", "group_id": 12345, "bounce": true, "click": true, "delivered": true, "dropped": true, "deferred": true, "open": true, "processed": true, "spam_report": true, "unsubscribe": true, "unique_args": {}, "asm_group_id": 123 } ] } ``` ``` -------------------------------- ### Clone and Set Up SendGrid Node.js Repository Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/docs/examples/webhooks-docker/CONTRIBUTING.md This snippet shows how to clone the SendGrid Node.js repository from GitHub, navigate into the directory, and set up the 'upstream' remote to point to the original repository. This is the initial step for contributing to the project. ```bash git clone https://github.com/sendgrid/sendgrid-nodejs cd sendgrid-nodejs git remote add upstream https://github.com/sendgrid/sendgrid-nodejs ``` -------------------------------- ### Retrieve a Global Suppression (Node.js) Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md This code example demonstrates how to retrieve information about a specific global suppression or verify if an email address is globally suppressed using the SendGrid Node.js SDK. It makes a GET request to '/v3/asm/suppressions/global/{email}'. ```javascript request.method = 'GET'; request.url = '/v3/asm/suppressions/global/{email}'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### Initialization and Authentication Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md This section covers how to initialize the SendGrid client and set your API key for authentication. It also demonstrates how to make API calls on behalf of a subuser. ```APIDOC ## Initialization ```javascript const client = require('@sendgrid/client'); client.setApiKey(process.env.SENDGRID_API_KEY); ``` ## On behalf of subusers Most API calls will accept an `on-behalf-of` header in order to make API calls as a given subuser: ```javascript // create an API key for the given subuser const data = { name: 'subuser API key', scopes: ['mail.send'], }; request.body = data; request.method = 'POST'; request.url = '/v3/api_keys'; request.headers = { 'On-Behalf-Of': 'subuser username' }; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }); ``` ``` -------------------------------- ### GET Client Statistics with Date Range (Node.js) Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md Retrieves statistics for clients, aggregated by a specified period. Requires setting query parameters for aggregation, start date, and end date. This method is useful for analyzing client activity over time. ```javascript const queryParams = { 'aggregated_by': 'day', 'end_date': '2016-04-01', 'start_date': '2016-01-01' }; request.qs = queryParams; request.method = 'GET'; request.url = '/v3/clients/{client_type}/stats'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### Clone and Set Up SendGrid Node.js Repository Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/CONTRIBUTING.md These bash commands guide you through forking the SendGrid Node.js project, cloning your fork locally, and setting up the 'upstream' remote to track the original repository. ```bash # Clone your fork of the repo into the current directory git clone https://github.com/sendgrid/sendgrid-nodejs # Navigate to the newly cloned directory cd sendgrid-nodejs # Assign the original repo to a remote called "upstream" git remote add upstream https://github.com/sendgrid/sendgrid-nodejs ``` -------------------------------- ### Retrieve Subuser Reputations with SendGrid Node.js Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md This example demonstrates retrieving the sender reputations for subusers using the SendGrid Node.js client. It sends a GET request to the /v3/subusers/reputations endpoint, accepting a 'usernames' query parameter. The output includes the response status code and body. ```javascript const queryParams = { 'usernames': 'test_string' }; request.qs = queryParams; request.method = 'GET'; request.url = '/v3/subusers/reputations'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### Instantiate Client Instances Manually Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/README.md Demonstrates how to create multiple independent instances of the SendGrid client, each with its own API key. This is beneficial for managing different SendGrid accounts or isolating configurations. ```APIDOC ## Instantiate Client Instances Manually ### Description Provides the ability to create and manage multiple, independent instances of the SendGrid client. Each instance can be configured with its own API key, allowing for concurrent operations with different SendGrid accounts or distinct configurations. ### Method N/A (Client Instantiation) ### Endpoint N/A ### Parameters None ### Request Example ```javascript const { Client } = require('@sendgrid/client'); const sgClient1 = new Client(); const sgClient2 = new Client(); sgClient1.setApiKey('YOUR_API_KEY_1'); sgClient2.setApiKey('YOUR_API_KEY_2'); // Now you can use sgClient1 and sgClient2 independently // For example: // sgClient1.request({...}); // sgClient2.request({...}); ``` ### Response N/A ``` -------------------------------- ### Clone and Set Up Local Repository with Upstream Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/FIRST_TIMERS.md This snippet demonstrates how to clone your forked repository, navigate into it, and set up the original repository as an 'upstream' remote. This is crucial for keeping your local copy synchronized with the main project. ```bash # Clone your fork of the repo into the current directory git clone https://github.com/your_username/sendgrid-nodejs # Navigate to the newly cloned directory cd sendgrid-nodejs # Assign the original repo to a remote called "upstream" git remote add upstream https://github.com/sendgrid/sendgrid-nodejs ``` -------------------------------- ### Set Twilio Environment Variables (Linux/Mac) Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/docs/use-cases/twilio-setup.md This snippet demonstrates how to export Twilio API credentials (either API key/secret or Account SID/Auth Token) to a 'twilio.env' file and then source it. It also includes adding the file to .gitignore. ```bash echo "export TWILIO_API_KEY='YOUR_TWILIO_API_KEY'" > twilio.env echo "export TWILIO_API_SECRET='YOUR_TWILIO_API_SECRET'" >> twilio.env # or echo "export TWILIO_ACCOUNT_SID='YOUR_TWILIO_ACCOUNT_SID'" > twilio.env echo "export TWILIO_AUTH_TOKEN='YOUR_TWILIO_AUTH_TOKEN'" >> twilio.env ``` ```bash echo "twilio.env" >> .gitignore source ./twilio.env ``` -------------------------------- ### Instantiate Client Instances Manually with SendGrid Client (Node.js) Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/README.md Demonstrates how to create multiple independent instances of the SendGrid client. This is useful when needing to manage different API keys or configurations simultaneously. Each instance can have its API key set independently. ```javascript const {Client} = require('@sendgrid/client'); const sgClient1 = new Client(); const sgClient2 = new Client(); sgClient1.setApiKey('KEY1'); sgClient2.setApiKey('KEY2'); ``` -------------------------------- ### GET /contactdb/status - Get Contact Upload Status Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md This endpoint retrieves the status of contact uploads to the recipient database. It makes a simple GET request to the '/v3/contactdb/status' endpoint. The response includes the status code and body, indicating the upload progress or completion. ```javascript request.method = 'GET'; request.url = '/v3/contactdb/status'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### Retrieve Credit Balance (GET /user/credits) Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md This snippet shows how to fetch the current credit balance for an account. The GET request is directed to the '/v3/user/credits' endpoint. ```javascript request.method = 'GET'; request.url = '/v3/user/credits'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### Retrieve Account Email Address (GET /user/email) Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md This code retrieves the email address currently associated with the user's account. The GET request is made to the '/v3/user/email' endpoint. ```javascript request.method = 'GET'; request.url = '/v3/user/email'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### Retrieve Subscription Tracking Settings (GET /tracking_settings/subscription) Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md This snippet demonstrates how to retrieve the current subscription tracking settings. It utilizes the GET method to request data from the '/v3/tracking_settings/subscription' endpoint. ```javascript request.method = 'GET'; request.url = '/v3/tracking_settings/subscription'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### Retrieve User Account Information (GET /user/account) Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md This code retrieves a user's account details, including their account type and reputation. The GET request is made to the '/v3/user/account' endpoint. ```javascript request.method = 'GET'; request.url = '/v3/user/account'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### GET All IPs in Warmup - Node.js Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md Retrieves a list of all IP addresses currently in warmup mode. Makes a GET request to the /v3/ips/warmup endpoint. Returns the status code and body of the response. ```javascript request.method = 'GET'; request.url = '/v3/ips/warmup'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### Run SendGrid Node.js Integration Tests with Docker Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/CONTRIBUTING.md This command executes all integration tests for the sendgrid-nodejs library using Docker. It requires Docker Desktop and 'make' to be installed. This command ensures tests are run in an isolated environment. ```bash make test-docker ``` -------------------------------- ### GET /contactdb/segments - Retrieve Segments Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md This endpoint retrieves all segments from the recipient database. It makes a GET request to the '/v3/contactdb/segments' endpoint. The response includes the status code and body of the API call. ```javascript request.method = 'GET'; request.url = '/v3/contactdb/segments'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### Run ESDoc for Documentation Coverage Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/CONTRIBUTING.md This command uses ESDoc to check the documentation coverage of your added code. Ensuring proper documentation is crucial for maintainability and understanding. ```bash yarn doc ``` -------------------------------- ### Get User Profile using SendGrid Node.js SDK Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md Retrieves the current user's profile details by sending a GET request to the /v3/user/profile endpoint. Requires the SendGrid Node.js SDK. ```javascript request.method = 'GET'; request.url = '/v3/user/profile'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### Initialize SendGrid Node.js Client Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md Initializes the SendGrid Node.js client by setting the API key from environment variables. This is a prerequisite for making any authenticated API calls. ```javascript const client = require('@sendgrid/client'); client.setApiKey(process.env.SENDGRID_API_KEY); ``` -------------------------------- ### Access Settings API Endpoints Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md Documentation for managing access settings, including retrieving activity logs and managing whitelist IPs. ```APIDOC ## GET /access_settings/activity ### Description This endpoint allows you to retrieve a list of all of the IP addresses that recently attempted to access your account either through the User Interface or the API. IP Access Management allows you to control which IP addresses can be used to access your account, either through the User Interface or the API. There is no limit to the number of IP addresses that you can add to your whitelist. It is possible to remove your IP address from the whitelist, thus preventing yourself from accessing your account. For more information, please see our [User Guide](http://sendgrid.com/docs/User_Guide/Settings/ip_access_management.html). ### Method GET ### Endpoint /v3/access_settings/activity ### Parameters #### Query Parameters - **limit** (integer) - Optional - Specifies the number of results to return. ### Request Example ```javascript const queryParams = { 'limit': 1 }; request.qs = queryParams; request.method = 'GET'; request.url = '/v3/access_settings/activity'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` ### Response #### Success Response (200) - **activity** (array) - A list of access attempt objects. - **ip** (string) - The IP address of the access attempt. - **last_seen** (string) - The timestamp of the last access attempt. #### Response Example ```json { "activity": [ { "ip": "1.2.3.4", "last_seen": "2016-09-10T10:00:00.000Z" } ] } ``` ``` ```APIDOC ## POST /access_settings/whitelist ### Description This endpoint allows you to add one or more IP addresses to your IP whitelist. When adding an IP to your whitelist, include the IP address in an array. You can whitelist one IP at a time, or you can whitelist multiple IPs at once. IP Access Management allows you to control which IP addresses can be used to access your account, either through the User Interface or the API. There is no limit to the number of IP addresses that you can add to your whitelist. It is possible to remove your IP address from the whitelist, thus preventing yourself from accessing your account. For more information, please see our [User Guide](http://sendgrid.com/docs/User_Guide/Settings/ip_access_management.html). ### Method POST ### Endpoint /v3/access_settings/whitelist ### Parameters #### Request Body - **ips** (array) - Required - An array of IP address objects to whitelist. - **ip** (string) - Required - The IP address or IP range to whitelist. ### Request Example ```javascript const data = { "ips": [ { "ip": "192.168.1.1" }, { "ip": "192.*.*.*" }, { "ip": "192.168.1.3/32" } ] }; request.body = data; request.method = 'POST'; request.url = '/v3/access_settings/whitelist'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "success": true } ``` ``` ```APIDOC ## DELETE /access_settings/whitelist ### Description This endpoint allows you to remove one or more IPs from your IP whitelist. You can remove one IP at a time, or you can remove multiple IP addresses. IP Access Management allows you to control which IP addresses can be used to access your account, either through the User Interface or the API. There is no limit to the number of IP addresses that you can add to your whitelist. It is possible to remove your IP address from the whitelist, thus preventing yourself from accessing your account. For more information, please see our [User Guide](http://sendgrid.com/docs/User_Guide/Settings/ip_access_management.html). ### Method DELETE ### Endpoint /v3/access_settings/whitelist ### Parameters #### Request Body - **ids** (array) - Required - An array of IP whitelist IDs to remove. ### Request Example ```javascript const data = { "ids": [ 1, 2, 3 ] }; request.body = data; request.method = 'DELETE'; request.url = '/v3/access_settings/whitelist'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### GET Remaining IPs Count - Node.js Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md Retrieves the count of IP addresses that can still be created and their associated costs. Makes a GET request to the /v3/ips/remaining endpoint. Returns the status code and body of the response. ```javascript request.method = 'GET'; request.url = '/v3/ips/remaining'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### Set Twilio Environment Variables (Windows - Temporary) Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/docs/use-cases/twilio-setup.md These commands temporarily set Twilio API credentials (either API key/secret or Account SID/Auth Token) for the current command-line session on Windows. ```batch set TWILIO_API_KEY=YOUR_TWILIO_API_KEY set TWILIO_API_SECRET=YOUR_TWILIO_API_SECRET : or set TWILIO_ACCOUNT_SID=YOUR_TWILIO_ACCOUNT_SID set TWILIO_AUTH_TOKEN=YOUR_TWILIO_AUTH_TOKEN ``` -------------------------------- ### GET /contactdb/segments/{segment_id} - Retrieve a Segment Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md This endpoint retrieves a single segment by its ID. It performs a GET request to '/v3/contactdb/segments/{segment_id}' with the segment ID as a query parameter. The response contains the segment details. ```javascript const queryParams = { 'segment_id': 1 }; request.qs = queryParams; request.method = 'GET'; request.url = '/v3/contactdb/segments/{segment_id}'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### Create monitor settings Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md Creates monitor settings for a subuser, enabling the receipt of outgoing message samples at a defined frequency. ```APIDOC ## POST /subusers/{subuser_name}/monitor ### Description Creates monitor settings for a subuser, enabling the receipt of outgoing message samples at a defined frequency. ### Method POST ### Endpoint /v3/subusers/{subuser_name}/monitor ### Parameters #### Path Parameters - **subuser_name** (string) - Required - The name of the subuser. #### Request Body - **email** (string) - Required - The email address to send the monitor samples to. - **frequency** (integer) - Required - The frequency (in emails) at which to send monitor samples. ### Request Example ```json { "email": "example@example.com", "frequency": 50000 } ``` ### Response #### Success Response (200) - **message** (string) - Indicates the success of the operation. #### Response Example ```json { "message": "success" } ``` ``` -------------------------------- ### Create Subuser Monitor Settings (Node.js) Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md Creates monitor settings for a SendGrid subuser, enabling you to receive message samples at a defined frequency. Input includes a notification email and frequency. ```javascript const data = { "email": "example@example.com", "frequency": 50000 }; request.body = data; request.method = 'POST'; request.url = '/v3/subusers/{subuser_name}/monitor'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### Use Multiple Client Instances Source: https://context7.com/sendgrid/sendgrid-nodejs/llms.txt Manage different SendGrid API connections simultaneously by creating and configuring multiple instances of the SendGrid client. ```APIDOC ## Use Multiple Client Instances ### Description Create separate client instances with different configurations. ### Method Various (used for different API calls) ### Endpoint Various SendGrid API endpoints ### Parameters When creating a new `Client` instance, you can optionally provide configuration such as: - **apiKey** (string) - API key for authentication. - **dataResidency** (string) - Data residency location (e.g., 'eu'). ### Request Example (Initializing clients) ```javascript const {Client} = require('@sendgrid/client'); // Client for main account const mainClient = new Client(); mainClient.setApiKey(process.env.SENDGRID_MAIN_KEY); // Client for subuser account const subuserClient = new Client(); subuserClient.setApiKey(process.env.SENDGRID_SUBUSER_KEY); // Client for EU data residency const euClient = new Client(); euClient.setApiKey(process.env.SENDGRID_API_KEY); euClient.setDataResidency('eu'); ``` ### Request Example (Making requests with different clients) ```javascript // Make requests with different clients const [mainResponse] = await mainClient.request({ method: 'GET', url: '/v3/user/profile' }); const [euResponse] = await euClient.request({ method: 'GET', url: '/v3/user/profile' }); ``` ### Response #### Success Response (200) - The `response` object will contain the status code and `body` will contain the API response data for the respective client's request. ``` -------------------------------- ### Retrieve Teammate Information (GET /teammates/{username}) Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md This snippet shows how to retrieve the details of a specific teammate using their username via a GET request. The response includes the teammate's status code and body. ```javascript request.method = 'GET'; request.url = '/v3/teammates/{username}'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### Set Twilio Environment Variables (Windows - Permanent) Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/docs/use-cases/twilio-setup.md These commands permanently set Twilio API credentials (either API key/secret or Account SID/Auth Token) for all subsequent command-line sessions on Windows using the 'setx' command. ```batch setx TWILIO_API_KEY "YOUR_TWILIO_API_KEY" setx TWILIO_API_SECRET "YOUR_TWILIO_API_SECRET" : or setx TWILIO_ACCOUNT_SID "YOUR_TWILIO_ACCOUNT_SID" setx TWILIO_AUTH_TOKEN "YOUR_TWILIO_AUTH_TOKEN" ``` -------------------------------- ### Get a list of all partner settings Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md Retrieves a list of all available partner settings. This endpoint can be used with query parameters for limiting and offsetting results. Requires the SendGrid Node.js client. ```javascript const queryParams = { 'limit': 1, 'offset': 1 }; request.qs = queryParams; request.method = 'GET'; request.url = '/v3/partner_settings'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### Install SendGrid Mail Package with npm or yarn Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/mail/README.md Instructions for installing the SendGrid mail package using either npm or yarn. This package is essential for integrating SendGrid's email sending capabilities into your Node.js application. ```sh npm install --save @sendgrid/mail ``` ```sh yarn add @sendgrid/mail ``` -------------------------------- ### Send Multiple Emails with Personalizations using SendGrid Node.js Helper Classes Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/docs/use-cases/multiple-emails-personalizations-with-substitutions.md This example demonstrates sending multiple emails with SendGrid using the '@sendgrid/helpers' classes. It constructs a 'Mail' object and adds multiple 'Personalization' objects, each with its own recipient and substitutions. This approach provides a more object-oriented way to manage email configurations. ```javascript const sgMail = require('@sendgrid/mail'); const sgHelpers = require('@sendgrid/helpers'); const Mail = sgHelpers.classes.Mail; const Personalization = sgHelpers.classes.Personalization; sgMail.setApiKey(process.env.SENDGRID_API_KEY); const mail = new Mail(); mail.setFrom('sender1@example.org'); mail.setSubject('Ahoy'); mail.addTextContent('Ahoy {{name}}!'); mail.addHtmlContent('

Ahoy {{name}}!

'); const personalization1 = new Personalization(); personalization1.setTo('recipient1@example.org'); personalization1.addSubstitution('name', 'Jon'); mail.addPersonalization(personalization1); const personalization2 = new Personalization(); personalization1.setTo('recipient2@example.org'); personalization1.addSubstitution('name', 'Jane'); mail.addPersonalization(personalization2); const personalization3 = new Personalization(); personalization1.setTo('recipient3@example.org'); personalization1.addSubstitution('name', 'Jack'); mail.addPersonalization(personalization3); sgMail.send(mail); ``` -------------------------------- ### POST /user/webhooks/parse/settings Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md Create a new inbound parse setting. ```APIDOC ## POST /user/webhooks/parse/settings ### Description This endpoint allows you to create a new inbound parse setting. ### Method POST ### Endpoint /v3/user/webhooks/parse/settings ### Parameters #### Query Parameters - None #### Request Body - **hostname** (string) - Required - The domain to use for inbound email parsing. - **send_raw** (boolean) - Optional - Whether to send the raw email content. - **spam_check** (boolean) - Optional - Whether to perform spam checks on incoming emails. - **url** (string) - Required - The URL to send the parsed email content to. ### Request Example ```json { "hostname": "myhostname.com", "send_raw": false, "spam_check": true, "url": "http://email.myhosthame.com" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates success. Example: "Success." #### Response Example ```json { "message": "Success." } ``` ``` -------------------------------- ### GET Specific Parse Setting by Hostname - Node.js Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md Retrieves a specific inbound parse setting using its hostname. This function performs a GET request to the SendGrid API endpoint for a single parse setting and logs the response status code and body. ```javascript request.method = 'GET'; request.url = '/v3/user/webhooks/parse/settings/{hostname}'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### Push Local Topic Branch to Fork Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/FIRST_TIMERS.md This command pushes your newly created and updated topic branch to your GitHub fork. This makes your changes available for creating a pull request. ```bash git push origin ``` -------------------------------- ### GET All Parse Settings - Node.js Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md Retrieves all configured inbound parse settings. This function makes a GET request to the relevant SendGrid API endpoint and logs the status code and body of the response. It's used to view existing parse configurations. ```javascript request.method = 'GET'; request.url = '/v3/user/webhooks/parse/settings'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### POST /campaigns Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md Creates a new marketing campaign. ```APIDOC ## POST /campaigns ### Description Creates a new marketing campaign. Subject, sender ID, content, and list/segment IDs are required to send or schedule the campaign, but not to create it. ### Method POST ### Endpoint /v3/campaigns ### Parameters #### Request Body - **title** (string) - Required - The title of the campaign. - **categories** (array of strings) - Optional - Categories to associate with the campaign. - **custom_unsubscribe_url** (string) - Optional - A custom unsubscribe URL. - **html_content** (string) - Required if sending/scheduling - The HTML content of the campaign. - **ip_pool** (string) - Optional - The IP pool to use for sending the campaign. - **list_ids** (array of integers) - Optional - IDs of the lists to send the campaign to. - **plain_content** (string) - Required if sending/scheduling - The plain text content of the campaign. - **segment_ids** (array of integers) - Optional - IDs of the segments to send the campaign to. - **sender_id** (integer) - Required if sending/scheduling - The ID of the sender. - **subject** (string) - Required if sending/scheduling - The subject line of the campaign. - **suppression_group_id** (integer) - Optional - The ID of the suppression group. ### Request Example ```json { "title": "March Newsletter", "categories": ["spring line"], "custom_unsubscribe_url": "", "html_content": "

Check out our spring line!

", "ip_pool": "marketing", "list_ids": [110, 124], "plain_content": "Check out our spring line!", "segment_ids": [110], "sender_id": 124451, "subject": "New Products for Spring!", "suppression_group_id": 42 } ``` ### Response #### Success Response (200) - **body** (object) - Contains details of the created campaign. #### Response Example ```json { "example": "response body containing campaign details" } ``` ``` -------------------------------- ### Run ESLint for Linting Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/CONTRIBUTING.md This command runs ESLint with the standard style guide to check for code style violations and potential errors. It helps maintain code consistency across the project. ```bash yarn lint ``` -------------------------------- ### GET Event Webhook Settings - Node.js Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md Retrieves the current configuration for SendGrid's event webhook. This involves making a GET request to the specified API endpoint using the SendGrid Node.js client. It logs the status code and response body. ```javascript request.method = 'GET'; request.url = '/v3/user/webhooks/event/settings'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### SendGrid Node.js: Get Subuser Associated Link Branding Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md Retrieves link branding associated with a subuser via the SendGrid Node.js client. This function performs a GET request to the /v3/whitelabel/links/subuser endpoint, requiring a 'username' query parameter to identify the subuser. ```javascript const queryParams = { 'username': 'test_string' }; request.qs = queryParams; request.method = 'GET'; request.url = '/v3/whitelabel/links/subuser'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### Send Email with Tracking and Settings using SendGrid Node.js Source: https://context7.com/sendgrid/sendgrid-nodejs/llms.txt Configure advanced email settings including click tracking, open tracking, subscription tracking, Google Analytics parameters, and footer content. This allows for detailed campaign analysis and customization. ```javascript const sgMail = require('@sendgrid/mail'); sgMail.setApiKey(process.env.SENDGRID_API_KEY); const msg = { to: 'user@example.com', from: 'marketing@company.com', subject: 'Campaign Email', html: '

Campaign content with tracking

', categories: ['marketing', 'campaign-2024'], customArgs: { campaignId: 'CAMP-123', userId: 'USER-456' }, trackingSettings: { clickTracking: { enable: true, enableText: true }, openTracking: { enable: true }, subscriptionTracking: { enable: true, text: 'To unsubscribe, click here: [unsubscribe]', html: '

To unsubscribe, click here

' }, ganalytics: { enable: true, utmSource: 'sendgrid', utmMedium: 'email', utmCampaign: 'spring-sale' } }, mailSettings: { sandboxMode: { enable: false }, footer: { enable: true, text: 'Company Name | 123 Street | City, State', html: '

Company Name | 123 Street | City, State

' } } }; await sgMail.send(msg); ``` -------------------------------- ### SendGrid Node.js: Get Default Whitelabel Link Branding Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md Retrieves the default whitelabel link branding configuration using the SendGrid Node.js client. This function makes a GET request to the /v3/whitelabel/links/default endpoint, optionally accepting a domain parameter for filtering. ```javascript const queryParams = { 'domain': 'test_string' }; request.qs = queryParams; request.method = 'GET'; request.url = '/v3/whitelabel/links/default'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### Run Specific SendGrid Node.js Tests Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/docs/examples/webhooks-docker/CONTRIBUTING.md Execute specific tests for SendGrid Node.js modules. After setting up the testing environment, you can run tests for individual packages like 'mail' or 'client'. ```bash yarn test:mail yarn test:client ``` -------------------------------- ### GET /contactdb/segments/{segment_id}/recipients - Retrieve Recipients in a Segment Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/packages/client/USAGE.md This endpoint retrieves all recipients belonging to a specific segment, identified by segment ID. It supports pagination via 'page' and 'page_size' query parameters. The request is a GET to '/v3/contactdb/segments/{segment_id}/recipients'. ```javascript const queryParams = { 'page': 1, 'page_size': 1 }; request.qs = queryParams; request.method = 'GET'; request.url = '/v3/contactdb/segments/{segment_id}/recipients'; client.request(request) .then(([response, body]) => { console.log(response.statusCode); console.log(response.body); }) ``` -------------------------------- ### Create a New Topic Branch for Contributions Source: https://github.com/sendgrid/sendgrid-nodejs/blob/main/FIRST_TIMERS.md This command creates a new branch based on the main development branch. This practice isolates your changes and makes it easier to manage contributions. ```bash git checkout -b ```