NodeJS
Send your mail using unsent in NodeJS
This guide shows how to install and use the official Unsent Node.js SDK.
Prerequisites
Before you begin, make sure you have the following:
Unsent API Key: You can generate one in your Unsent dashboard.
Verified Domain: You need a verified domain to send emails. Set this up in the Domains section.
Using SDK
Install SDK
Install the @unsent/sdk package using your preferred package manager:
npm install @unsent/sdkpnpm add @unsent/sdkyarn add @unsent/sdkbun add @unsent/sdkInitialize SDK
Import the SDK and initialize the client with your API key.
import { unsent } from "@unsent/sdk";
const client = new unsent("un_xxxx");Send Email
Now you can send an email. Use the client.emails.send method and provide the email details such as to, from, subject, and html content.
const { data, error } = await client.emails.send({
to: "hello@acme.com",
from: "hello@company.com",
subject: "unsent email",
html: "<p>unsent is the best provider to send emails</p>",
text: "hello from unsent",
headers: {
"X-Campaign": "welcome",
},
}, {
idempotencyKey: "unique-key-123"
});
if (error) {
console.error("Failed to send email:", error);
} else {
console.log("Email sent successfully:", data);
}Note
Custom headers are forwarded as-is. Unsent automatically manages the X-Unsent-Email-ID and References headers for you.
Adding contacts programmatically
You can manage your contacts directly via the API. First, you'll need a Contact Book ID.
Get the contact book id
Go to the Contacts section in your dashboard and copy the ID of the contact book you want to use.
Add contacts
To add a new contact to your book, use the client.contacts.create method:
const { data, error } = await client.contacts.create("clzeydgeygff", {
email: "hey@koushik.dev",
firstName: "Koushik",
lastName: "KM",
});
if (error) {
console.error(error);
} else {
console.log("Contact added:", data);
}Update contact
To update an existing contact's information, use the client.contacts.update method with the contact ID:
const { data, error } = await client.contacts.update("clzeydgeygff", "contact_id_here", {
firstName: "Koushik",
lastName: "KM",
});
if (error) {
console.error(error);
} else {
console.log("Contact updated:", data);
}Upsert contact
To create or update a contact based on their email address, use the client.contacts.upsert method:
const { data, error } = await client.contacts.upsert("clzeydgeygff", "contact_id_here", {
email: "hey@koushik.dev",
firstName: "Koushik",
lastName: "KM",
});Batch Sending
If you need to send many emails at once, use the batch sending feature. You can send up to 100 emails in a single API call using client.emails.batch.
const { data, error } = await client.emails.batch([
{
to: "user1@example.com",
from: "hello@company.com",
subject: "Hello 1",
html: "<p>Hello 1</p>",
},
{
to: "user2@example.com",
from: "hello@company.com",
subject: "Hello 2",
html: "<p>Hello 2</p>",
},
], {
idempotencyKey: "batch-unique-key-123"
});Retrieve and Manage Emails
You can retrieve details about sent emails or manage scheduled ones.
Get an email
Fetch the status and details of a specific email using its ID:
const { data, error } = await client.emails.get("email_123");Update schedule time
Change the scheduled delivery time for a pending email:
const { data, error } = await client.emails.update("email_123", {
scheduledAt: new Date(Date.now() + 3600000), // Reschedule to 1 hour from now
});Cancel a scheduled email
Cancel a scheduled email so it won't be sent:
const { data, error } = await client.emails.cancel("email_123");Campaigns
Campaigns allow you to send emails to an entire contact book.
Create a campaign
Create a new campaign targeting a specific contact book:
const { data, error } = await client.campaigns.create({
name: "Welcome Series",
subject: "Welcome!",
html: "<p>Thanks for joining us!</p>",
from: "welcome@yourdomain.com",
contactBookId: "book_123",
});Schedule a campaign
Set a time for your campaign to start sending:
const { data, error } = await client.campaigns.schedule("campaign_123", {
scheduledAt: "2024-12-01T10:00:00Z",
});Pause and Resume
Control the delivery of your campaign:
// Pause the campaign
await client.campaigns.pause("campaign_123");
// Resume the campaign
await client.campaigns.resume("campaign_123");Domains
Manage your sending domains programmatically.
List domains
Get a list of all domains and their statuses:
const { data, error } = await client.domains.list();Create a domain
Register a new domain for sending:
const { data, error } = await client.domains.create({
domain: "yourdomain.com",
region: "us-east-1",
});Verify a domain
Check the verification status of a domain:
const { data, error } = await client.domains.verify(123);Error Handling
The SDK uses a consistent error handling pattern. Methods return an object containing either data (on success) or error (on failure).
const { data, error } = await client.emails.send({ ... });
if (error) {
// Handle the error gracefully
console.error(`Error ${error.statusCode}: ${error.message}`);
} else {
// Proceed with the successful response
console.log("Success:", data.id);
}