sendgrid-nodejs

repository·main·Indexed 25 days ago

https://github.com/sendgrid/sendgrid-nodejs

A monorepo of Node.js packages for interacting with the Twilio SendGrid Web API v3. It includes @sendgrid/client for core API requests, @sendgrid/mail for sending emails, @sendgrid/inbound-mail-parser for processing inbound mail, and @sendgrid/helpers for composing API objects like Mail, Attachment, and Personalization. The library supports Node.js versions 6, 8, and >=10.

Tokens
65.1K
Snippets
218
Records
305
Agent score
84%

What's inside sendgrid-nodejs

  1. Overview of SendGrid Node.js packages

    main

    The sendgrid-nodejs repository is a monorepo containing several specialized packages. You should install only the packages necessary for your specific use case to keep your project lightweight.

    Key packages include:

    • @sendgrid/mail: Use this if your primary goal is to send emails.
    • @sendgrid/client: Use this to access all other Twilio SendGrid v3 Web API endpoints.
    • @sendgrid/inbound-mail-parser: Provides assistance with parsing the Twilio SendGrid Inbound Parse API.
    • @sendgrid/contact-importer: Provides assistance with importing contacts into the ContactDB.
    • @sendgrid/eventwebhook: Provides assistance with validating events sent by SendGrid to your event webhook.
    • @sendgrid/helpers: A collection of internal classes and helpers used by the other packages.
  2. Overview of @sendgrid/helpers

    main
    The @sendgrid/helpers package provides support classes and utility functions used by the SendGrid NodeJS libraries. While many of these classes are used internally, they provide structured ways to compose objects for the SendGrid v3 API, such as Mail, Attachment, and Personalization objects.
  3. Select the appropriate SendGrid package

    main

    This repository is a monorepo containing several specialized packages. Choose the package that matches your specific use case:

    • @sendgrid/mail: Use this if your primary goal is to send emails.
    • @sendgrid/client: Use this to access all other SendGrid v3 Web API endpoints.
    • @sendgrid/inbound-mail-parser: Use this to assist with parsing the SendGrid Inbound Parse API.
    • @sendgrid/contact-importer: Use this to assist with importing contacts into the ContactDB.
    • @sendgrid/helpers: A collection of utility classes and helpers used internally by the other packages.
  4. Migrate from version 6.X.X to 7.X.X

    main

    When upgrading from version 6.X.X to 7.X.X, the underlying HTTP client was changed from request to axios. This change affects how request and response objects are structured.

    Key Changes

    • Untethered Interfaces: The ClientRequest and ClientResponse objects no longer expose raw interfaces from the request module. They now use internal interfaces that mask implementation details to allow for the switch to axios.
    • Breaking Changes for Custom Options: If your code passes undocumented request options directly to the HTTP client, these may no longer be supported.
    • Breaking Changes for Response Data: If your code relies on specific HTTP response data that was previously available via the request module, you must update your logic to use the properties exposed by the new ClientResponse object.

    Migration Steps

    1. Identify code utilizing request or response properties that are no longer exposed in the new interfaces.
    2. Update response handling to use the new ClientResponse object.
    3. Update request configuration to use the options defined in the RequestOptions interface.
  5. Request and download Email Activity CSV

    main

    You can generate a CSV containing the last 1 million messages.

    1. Request the CSV: Use POST /messages/download. This triggers a background process. Once ready, the account owner receives an email with a download link. The link expires in 3 days.
    2. Download the CSV: Use GET /messages/download/{download_uuid} to retrieve the file.

    Constraints:

    // Requesting the CSV
      request.method = 'POST';
      request.url = '/v3/messages/download';
      client.request(request)
      .then(([response, body]) => {
        console.log(response.statusCode);
        console.log(response.body);
      })
    
    // Downloading the CSV
      request.method = 'POST'; // Note: Documentation shows POST for the download endpoint
      request.url = '/v3/messages/download/{download_uuid}';
      client.request(request)
      .then(([response, body]) => {
        console.log(response.statusCode);
        console.log(response.body);
      })
  6. Setup Domain Authentication

    main

    Domain authentication can be configured through the Twilio SendGrid UI or via the API.

    • UI Setup: Follow the official SendGrid guide for account and settings configuration.
    • API Setup: Use the @sendgrid/client package to manage sender authentication programmatically. Refer to the sender-authentication section in the client package documentation for specific API implementation details.
  7. Send multiple emails with personalizations

    main

    You can send multiple distinct emails in a single API request by using the personalizations array. Each object in the personalizations array allows you to customize metadata such as recipients (setTo), CC recipients (setCc), the sender (setFrom), and the subject line (setSubject) for that specific email.

    To implement this, use the Personalization class from @sendgrid/helpers to create individual personalization objects and push them into the personalizations array of your message object.

    const sgMail = require('@sendgrid/mail');
    const sgHelpers = require('@sendgrid/helpers');
    const Personalization = sgHelpers.classes.Personalization;
    
    sgMail.setApiKey(process.env.SENDGRID_API_KEY);
    const msg = {
        from: 'sender1@example.org',
        subject: 'Hello world',
        text: 'Hello plain world!',
        html: '<p>Hello HTML world!</p>',
        personalizations: []
    };
    
    const personalization1 = new Personalization();
    personalization1.setTo(['recipient2@example.org', 'recipient3@example.org']);
    personalization1.setCc('recipient4@example.org');
    msg.personalizations.push(personalization1);
    
    const personalization2 = new Personalization();
    personalization2.setTo(['recipient5@example.org', 'recipient6@example.org', 'recipient7@example.org']);
    personalization2.setFrom('sender2@example.org');
    personalization2.setCc('recipient8@example.org');
    msg.personalizations.push(personalization2);
    
    const personalization3 = new Personalization();
    personalization3.setTo('recipient9@example.org');
    personalization3.setFrom('sender3@example.org');
    personalization3.setCc('recipient10@example.org');
    personalization3.setSubject('Greetings world');
    msg.personalizations.push(personalization3);
    
    sgMail.send(msg);
  8. Manage Marketing Campaigns

    main

    The Marketing Campaigns API allows you to create, manage, send, and schedule campaigns.

    • Create a Campaign: POST /v3/campaigns. Requires parameters like subject, sender_id, and content. Note that list_ids or segment_ids are required to actually send/schedule.
    • Retrieve all Campaigns: GET /v3/campaigns. Returns campaigns in reverse order of creation (newest first).
    • Retrieve a single campaign: GET /v3/campaigns/{campaign_id}.
    • Update a Campaign: PATCH /v3/campaigns/{campaign_id}. Useful for updating parameters like subject or html_content after creation.
    • Delete a Campaign: DELETE /v3/campaigns/{campaign_id}.
    • Schedule a Campaign: POST /v3/campaigns/{campaign_id}/schedules with a send_at Unix timestamp.
    • Unschedule a Campaign: DELETE /v3/campaigns/{campaign_id}/schedules. Returns a 204 on success. If the campaign is already in the process of being sent, you must use the cancel method instead.