> ## Documentation Index
> Fetch the complete documentation index at: https://nuntly.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Migrate from SendGrid

> Move transactional email from SendGrid to Nuntly in four steps. Set up your domain and key, swap the SDK or SMTP, move your webhooks, then test and cut over.

Move an app that sends transactional email with a SendGrid SDK or SMTP to Nuntly, in TypeScript or Java. The four steps follow a real migration and keep a way back until the end.

## Prerequisites

* A Nuntly account. See [account setup](https://nuntly.com/docs/guides/account-setup.md).
* Access to the DNS records of the domain you send from.

> [!NOTE]
>
> SendGrid facts on this page come from Twilio SendGrid's own documentation and SDKs, read on November 16, 2026. The code samples compile with `@nuntly/sdk` 2.0.0, `@sendgrid/mail` 8.1.6, `@sendgrid/eventwebhook` 8.0.0 and `nodemailer` 10.6.0 under TypeScript `strict`, and with `com.nuntly:nuntly-java` 2.0.0 and `com.sendgrid:sendgrid-java` 4.10.3 on Java 21.

> [!TIP]
>
> An AI coding agent can make the code changes of step 2 for you, then list the calls it could not map. See [Use Nuntly from an AI agent](https://nuntly.com/docs/guides/ai-agents.md). The other steps stay with you.

## Step 1: Set up Nuntly

### Verify your sending domain

Add the domain you send from today. You do not need to remove anything from SendGrid first.

1. In the Nuntly dashboard, go to **Domains** and click **Add Domain**.
2. Add the DKIM, SPF and MX records Nuntly shows to your DNS provider. DMARC is recommended but never blocks verification. You can import all records at once with the zone file. See [sending domains](https://nuntly.com/docs/guides/sending-domains.md).
3. The domain shows as verified once your DNS provider publishes the records, which takes from a few minutes to a few hours.

Keep SendGrid's records in place. Nuntly's DKIM, SPF and MX records use names of their own, so both sets work on the same domain without conflict. If you publish a DMARC record already, keep it: one `_dmarc` record covers both providers.

If you track opens or clicks with SendGrid, turn on open and click tracking on the Nuntly domain once it is verified. Nuntly sets tracking per domain, for every email sent from it. See [open and click tracking](https://nuntly.com/docs/guides/sending-domains.md#enable-open-and-click-tracking).

### Create an API key

1. In the dashboard, go to **API Keys** and click **Create API Key**.
2. Pick **Sending only** for an app that only sends, and limit it to the domain above. Pick **Full access** only for code that also reads emails or manages domains, webhooks or keys.
3. Copy the key. It starts with `ntly_` and is shown once.

Store it next to your SendGrid key, under a new name:

```bash .env theme={null}
SENDGRID_API_KEY=SG.your_sendgrid_key
NUNTLY_API_KEY=ntly_your_api_key
```

Keeping both keys during the migration lets you switch providers with a flag in step 4. See [API keys](https://nuntly.com/docs/guides/api-keys.md) for permissions and domain restrictions.

## Step 2: Swap the SDK

### Move over SMTP first

To move traffic before you touch the send code, point your SMTP settings at Nuntly first, then swap in the SDK once delivery looks right. Change the host to `smtp.nuntly.com`, the port to `587` with STARTTLS, the username to `nuntly` and the password to your Nuntly API key.

With nodemailer, only the transport changes:

```typescript theme={null}
import nodemailer from 'nodemailer';

const transport = nodemailer.createTransport({
  host: 'smtp.nuntly.com',
  port: 587,
  secure: false, // STARTTLS on port 587
  auth: { user: 'nuntly', pass: process.env.NUNTLY_API_KEY },
});
```

See [SMTP](https://nuntly.com/docs/guides/send-emails-with-smtp.md) for the supported ports and the common connection errors.

### Swap the send call

Install the Nuntly SDK next to the SendGrid one. Remove the SendGrid SDK only after the cut-over.

```bash npm theme={null}
npm install @nuntly/sdk
```

```bash pnpm theme={null}
pnpm add @nuntly/sdk
```

```bash yarn theme={null}
yarn add @nuntly/sdk
```

```bash bun theme={null}
bun add @nuntly/sdk
```

```xml Maven theme={null}
<dependency>
  <groupId>com.nuntly</groupId>
  <artifactId>nuntly-java</artifactId>
  <version>2.0.0</version>
</dependency>
```

```kotlin Gradle theme={null}
implementation("com.nuntly:nuntly-java:2.0.0")
```

The same order-shipped email, before and after. Categories and custom args both become tags, whose names and values accept letters, digits, `_` and `-`:

```typescript SendGrid (TypeScript) theme={null}
import sgMail from '@sendgrid/mail';

sgMail.setApiKey(process.env.SENDGRID_API_KEY!);

try {
  const [response] = await sgMail.send({
    from: 'Acme <hello@yourdomain.com>',
    to: 'user@example.com',
    replyTo: 'support@yourdomain.com',
    subject: 'Your order has shipped',
    html: '<p>Your package is on the way.</p>',
    text: 'Your package is on the way.',
    categories: ['shipping'],
    customArgs: { orderId: '1234' },
  });
  console.log('Accepted', response.statusCode);
} catch (err) {
  console.error('Email not sent', err);
}
```

```typescript Nuntly (TypeScript) theme={null}
import { APIError, Nuntly } from '@nuntly/sdk';

const nuntly = new Nuntly({ apiKey: process.env.NUNTLY_API_KEY });

try {
  const sent = await nuntly.emails.send({
    from: 'Acme <hello@yourdomain.com>',
    to: 'user@example.com',
    replyTo: 'support@yourdomain.com',
    subject: 'Your order has shipped',
    html: '<p>Your package is on the way.</p>',
    text: 'Your package is on the way.',
    tags: [
      { name: 'category', value: 'shipping' },
      { name: 'orderId', value: '1234' },
    ],
  });
  console.log('Accepted', sent.id, sent.status);
} catch (err) {
  if (err instanceof APIError) {
    console.error('Email not sent', err.status, err.code, err.requestId);
  } else {
    throw err;
  }
}
```

```java SendGrid (Java) theme={null}
import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.Response;
import com.sendgrid.SendGrid;
import com.sendgrid.helpers.mail.Mail;
import com.sendgrid.helpers.mail.objects.Content;
import com.sendgrid.helpers.mail.objects.Email;
import java.io.IOException;

class SendGridSendBefore {
  void send() {
    SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));

    Mail mail = new Mail(
        new Email("hello@yourdomain.com", "Acme"),
        "Your order has shipped",
        new Email("user@example.com"),
        new Content("text/html", "<p>Your package is on the way.</p>"));
    mail.setReplyTo(new Email("support@yourdomain.com"));
    mail.addCategory("shipping");
    mail.addCustomArg("orderId", "1234");

    try {
      Request request = new Request();
      request.setMethod(Method.POST);
      request.setEndpoint("mail/send");
      request.setBody(mail.build());
      Response response = sg.api(request);
      System.out.println("Accepted " + response.getStatusCode());
    } catch (IOException e) {
      System.err.println("Email not sent: " + e.getMessage());
    }
  }
}
```

```java Nuntly (Java) theme={null}
import com.nuntly.sdk.ApiError;
import com.nuntly.sdk.Nuntly;
import com.nuntly.sdk.models.CreateEmailRequest;
import com.nuntly.sdk.models.CreateEmailResponse;
import com.nuntly.sdk.models.Tag;
import java.util.List;

class NuntlySendAfterSendGrid {
  void send() {
    Nuntly nuntly = Nuntly.create(Nuntly.builder().apiKey(System.getenv("NUNTLY_API_KEY")).build());

    CreateEmailRequest email = CreateEmailRequest.builder()
        .from("Acme <hello@yourdomain.com>")
        .to(List.of("user@example.com"))
        .replyTo(List.of("support@yourdomain.com"))
        .subject("Your order has shipped")
        .html("<p>Your package is on the way.</p>")
        .tags(List.of(
            Tag.builder().name("category").value("shipping").build(),
            Tag.builder().name("orderId").value("1234").build()))
        .build();

    try {
      CreateEmailResponse sent = nuntly.emails().send(email);
      System.out.println("Accepted " + sent.id() + " " + sent.status());
    } catch (ApiError e) {
      System.err.println("Email not sent: " + e.status() + " " + e.code());
    }
  }
}
```

Store the returned email ID with your order if you track email status: it is the `data.id` of every webhook event for that email. Two behaviors to know:

* **Idempotency is on by default.** Without an idempotency key, the Nuntly SDKs generate one for each send and reuse it across their own retries, so an automatic retry cannot send twice. Pass your own key to deduplicate across calls. See [idempotency keys](https://nuntly.com/docs/guides/idempotency.md).
* **Errors are typed.** The client throws an `APIError` (TypeScript) or an `ApiError` subclass (Java) with the status and an error code. A network failure throws a connection error, which the TypeScript sample rethrows. See [errors](https://nuntly.com/docs/api-reference/errors.md).

### Personalizations

A SendGrid request with several `personalizations` becomes a bulk request with one email per recipient. Shared values move to `fallback`, and the HTML is rendered in your code:

```typescript theme={null}
import { Nuntly } from '@nuntly/sdk';

const nuntly = new Nuntly({ apiKey: process.env.NUNTLY_API_KEY });

const escapeHtml = (value: string) =>
  value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');

const recipients = [
  { email: 'ana@example.com', name: 'Ana' },
  { email: 'ben@example.com', name: 'Ben' },
];

const bulk = await nuntly.emails.bulk.send({
  fallback: {
    from: 'Acme <hello@yourdomain.com>',
    subject: 'Your weekly report',
  },
  emails: recipients.map((r) => ({
    to: r.email,
    html: `<p>Hi ${escapeHtml(r.name)}, here is your report.</p>`,
  })),
});

console.log(bulk.id, bulk.emails.length);
```

Send more than 20 recipients in several calls. Escape any value you insert into HTML.

## Step 3: Move your webhooks

In the Nuntly dashboard, go to **Webhooks**, click **Create Webhook**, enter your endpoint URL and select the events you handle. Each event and its payload are described in [sending events](https://nuntly.com/docs/guides/sending-webhooks.md). Copy the signing secret into `NUNTLY_WEBHOOK_SECRET`: it is shown once. See [set up webhooks](https://nuntly.com/docs/guides/webhooks.md).

The handler, before and after. Both read the raw body, so in Express register the route before any JSON body parser:

```typescript SendGrid (TypeScript) theme={null}
import express from 'express';
import { EventWebhook, EventWebhookHeader } from '@sendgrid/eventwebhook';

const app = express();
const verifier = new EventWebhook();
const publicKey = verifier.convertPublicKeyToECDSA(process.env.SENDGRID_WEBHOOK_PUBLIC_KEY!);

app.post('/webhooks/email', express.raw({ type: 'application/json' }), (req, res) => {
  const signature = req.get(EventWebhookHeader.SIGNATURE()) ?? '';
  const timestamp = req.get(EventWebhookHeader.TIMESTAMP()) ?? '';
  if (!verifier.verifySignature(publicKey, req.body, signature, timestamp)) {
    return res.status(401).json({ error: 'invalid_signature' });
  }

  const events: Array<{ event: string; sg_message_id: string; type?: string }> = JSON.parse(req.body.toString());
  for (const e of events) {
    switch (e.event) {
      case 'delivered':
        console.log(`Email ${e.sg_message_id} delivered`);
        break;
      case 'bounce':
        console.log(`Email ${e.sg_message_id} bounced (${e.type})`);
        break;
      case 'spamreport':
        console.log(`Email ${e.sg_message_id} marked as spam`);
        break;
      default:
        console.log(`Unhandled event ${e.event}`);
    }
  }

  res.json({ received: true });
});
```

```typescript Nuntly (TypeScript) theme={null}
import express from 'express';
import { verifyWebhook, WebhookVerificationError } from '@nuntly/sdk';

const app = express();

app.post('/webhooks/email', express.raw({ type: 'application/json' }), async (req, res) => {
  let event;
  try {
    event = await verifyWebhook(req.body, req.get('webhook-signature') ?? '', process.env.NUNTLY_WEBHOOK_SECRET!);
  } catch (err) {
    if (err instanceof WebhookVerificationError) {
      return res.status(401).json({ error: 'invalid_signature' });
    }
    throw err;
  }

  switch (event.type) {
    case 'email.delivered':
      console.log(`Email ${event.data.id} delivered`);
      break;
    case 'email.bounced':
      console.log(`Email ${event.data.id} bounced (${event.data.bounce.bounceType})`);
      break;
    case 'email.complained':
      console.log(`Email ${event.data.id} marked as spam`);
      break;
    default:
      console.log(`Unhandled event ${event.type}`);
  }

  res.json({ received: true });
});
```

```java SendGrid (Java) theme={null}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sendgrid.helpers.eventwebhook.EventWebhook;
import java.security.interfaces.ECPublicKey;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@RestController
class SendGridWebhookController {
  private final EventWebhook verifier = new EventWebhook();
  private final ObjectMapper json = new ObjectMapper();

  @PostMapping("/webhooks/email")
  ResponseEntity<Void> receive(
      @RequestBody String payload,
      @RequestHeader("X-Twilio-Email-Event-Webhook-Signature") String signature,
      @RequestHeader("X-Twilio-Email-Event-Webhook-Timestamp") String timestamp) throws Exception {
    ECPublicKey publicKey = verifier.ConvertPublicKeyToECDSA(System.getenv("SENDGRID_WEBHOOK_PUBLIC_KEY"));
    if (!verifier.VerifySignature(publicKey, payload, signature, timestamp)) {
      return ResponseEntity.status(401).build();
    }

    for (JsonNode e : json.readTree(payload)) {
      String messageId = e.path("sg_message_id").asText();
      switch (e.path("event").asText()) {
        case "delivered" -> System.out.println("Email " + messageId + " delivered");
        case "bounce" -> System.out.println("Email " + messageId + " bounced (" + e.path("type").asText() + ")");
        case "spamreport" -> System.out.println("Email " + messageId + " marked as spam");
        default -> System.out.println("Unhandled event " + e.path("event").asText());
      }
    }
    return ResponseEntity.ok().build();
  }
}
```

```java Nuntly (Java) theme={null}
import com.nuntly.sdk.lib.Webhook;
import com.nuntly.sdk.lib.WebhookVerificationError;
import com.nuntly.sdk.models.EmailBouncedEvent;
import com.nuntly.sdk.models.EmailComplainedEvent;
import com.nuntly.sdk.models.EmailDeliveredEvent;
import com.nuntly.sdk.models.WebhookEvent;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@RestController
class NuntlyWebhookController {
  @PostMapping("/webhooks/email")
  ResponseEntity<Void> receive(
      @RequestBody String payload,
      @RequestHeader(name = "webhook-signature", required = false) String signature) {
    WebhookEvent event;
    try {
      event = Webhook.verify(payload, signature, System.getenv("NUNTLY_WEBHOOK_SECRET"));
    } catch (WebhookVerificationError e) {
      return ResponseEntity.status(401).build();
    }

    switch (event) {
      case EmailDeliveredEvent e -> System.out.println("Email " + e.data().id() + " delivered");
      case EmailBouncedEvent e -> System.out.println(
          "Email " + e.data().id() + " bounced (" + e.data().bounce().bounceType() + ")");
      case EmailComplainedEvent e -> System.out.println("Email " + e.data().id() + " marked as spam");
      default -> System.out.println("Unhandled event " + event.type());
    }
    return ResponseEntity.ok().build();
  }
}
```

The Nuntly verification rejects a request whose signature does not match or whose timestamp is more than 5 minutes old. It returns a typed event: TypeScript narrows `event.data` in each `case`, and Java matches one record per event type. When your endpoint fails, Nuntly retries with exponential backoff, and you can replay a delivery from the [webhooks observability view](https://nuntly.com/docs/guides/observability-webhooks.md).

Run both handlers during the migration: SendGrid keeps sending events for the emails it delivered, and Nuntly sends events for its own.

### Carry over your suppressions

Before your first Nuntly send, export your SendGrid bounces, blocks, spam reports, invalid emails and unsubscribes, keep them in your app, and skip those addresses before you call the send. From then on, Nuntly adds permanent bounces and spam complaints to its own suppression list, and an email to a suppressed address triggers `email.rejected`.

## Step 4: Test and cut over

### Send a test

Send to an inbox you own, from the verified domain, with the new key:

1. Send one email with the code from step 2.
2. In the dashboard, open **Emails**, select the email by its ID, and open **Email Timeline** to see its events.
3. Check that your webhook endpoint receives `email.delivered`, and that the signature check passes.
4. Open the email in the inbox and check the headers: DKIM should pass for your domain.

Then run your existing test suite against the Nuntly client to catch any field you forgot to map.

### Cut over

Switch providers with a configuration flag, and keep the SendGrid code until the cut-over is done:

1. Read the provider from configuration, for example `EMAIL_PROVIDER=nuntly`, and keep both clients in the code.
2. Move one message type at a time. Start with low-risk email such as notifications, watch bounces and complaints in the [observability dashboard](https://nuntly.com/docs/guides/observability.md), then move password resets and receipts.
3. Keep SendGrid's DNS records, API key and Event Webhook active until no traffic has gone through SendGrid for a few days. Sends already scheduled on SendGrid still go out from SendGrid: cancel them there and schedule them again on Nuntly, or let them run out.

When you are done, remove the SendGrid DNS records, delete the SendGrid API key and Event Webhook, and remove the SendGrid SDK from your dependencies.

## Next steps

> [card] [Send email from Express](https://nuntly.com/docs/guides/send-email-from-express.md)
>
> A full Express app with sending, webhooks and error handling

> [card] [Send email from Spring Boot](https://nuntly.com/docs/guides/send-email-from-spring-boot.md)
>
> The Spring Boot starter, sending and a verified webhook controller

> [card] [Idempotency keys](https://nuntly.com/docs/guides/idempotency.md)
>
> Key formats, strategies and error codes

> [card] [Migrate from Resend](https://nuntly.com/docs/guides/migrate-from-resend.md)
>
> The same steps for a Resend integration


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.