unsent
unsent.dev
Get Started

Java

Official Unsent Java SDK for sending emails and managing contacts.

This guide shows how to install and use the official Unsent Java SDK.

Installation

To get started, you need to add the unsent-java library to your project. If you are using Maven, add the following dependency to your pom.xml file:

<dependency>
  <groupId>dev.unsent</groupId>
  <artifactId>unsent-java</artifactId>
  <version>1.0.2</version>
</dependency>

Initialize

Next, initialize the client with your API key. You can find your API key in the Unsent dashboard.

Create an instance of UnsentClient:

import dev.unsent.UnsentClient;

// With implicit API key from environment variable UNSENT_API_KEY
UnsentClient client = new UnsentClient();

// Or explicit initialization
UnsentClient client = new UnsentClient("un_xxx");

Send an email

Now you are ready to send an email. We recommend using the provided builder pattern for cleaner code.

import dev.unsent.types.SendEmailRequest;
import dev.unsent.types.SendEmailRequestTo;

// Use the builder pattern
SendEmailRequest email = new SendEmailRequest()
    .to(new SendEmailRequestTo("user@example.com"))
    .from("no-reply@yourdomain.com")
    .subject("Welcome")
    .html("<strong>Hello!</strong>");

client.emails.send(email);

Advanced Email Features

Attachments

You can send attachments by providing a list of maps containing the filename and base64 encoded content.

import java.util.List;
import java.util.Map;

Map<String, Object> attachment = Map.of(
    "filename", "report.pdf",
    "content", "JVBERi0xLjQ..." // Base64 encoded content
);

SendEmailRequest email = new SendEmailRequest()
    // ... basic fields
    .attachments(List.of(attachment));
    
client.emails.send(email);

Scheduling

Schedule emails to be sent at a specific time using ISO 8601 format.

import dev.unsent.types.SendEmailRequest;

SendEmailRequest email = new SendEmailRequest()
    // ... basic fields
    .scheduledAt("2024-12-01T10:00:00Z");

client.emails.send(email);

Batch Sending

To send multiple emails efficiently in a single request:

import java.util.List;

List<SendEmailRequest> batch = new ArrayList<>();
batch.add(email1);
batch.add(email2);

client.emails.batch(batch);

Contacts & Lists

Manage your contacts and organize them into contact books (lists).

Create Contact Book

import dev.unsent.types.CreateContactBookRequest;

CreateContactBookRequest book = new CreateContactBookRequest()
    .name("Newsletter Subscribers");

client.contactBooks.create(book);

Manage Contacts

import dev.unsent.types.CreateContactRequest;

// Create a contact
CreateContactRequest contact = new CreateContactRequest()
    .email("jane@example.com")
    .firstName("Jane")
    .lastName("Doe")
    .metadata(Map.of("plan", "premium"));

client.contacts.create("book_id", contact);

// Upsert (Create or Update)
client.contacts.upsert("book_id", "contact_id", contact);

// List contacts
client.contacts.list("book_id");

Campaigns

Create and manage email campaigns for your contact lists.

import dev.unsent.types.CreateCampaignRequest;
import dev.unsent.types.ScheduleCampaignRequest;

// 1. Create Campaign
CreateCampaignRequest campaign = new CreateCampaignRequest()
    .name("Weekly Digest")
    .subject("Here is your digest")
    .html("<p>...</p>")
    .contactBookId("book_id");

client.campaigns.create(campaign);

// 2. Schedule
client.campaigns.schedule("campaign_id", 
    new ScheduleCampaignRequest().scheduledAt("2024-12-01T09:00:00Z")
);

// 3. Pause/Resume
client.campaigns.pause("campaign_id");
client.campaigns.resume("campaign_id");

Domains

Programmatically manage your sending domains and access domain-specific analytics.

import dev.unsent.types.Types.CreateDomainRequest;

// Add a domain
client.domains.create(new CreateDomainRequest().name("example.com"));

// Verify domain (checks DNS records)
client.domains.verify("domain_id");

// List all domains
client.domains.list();

// Get domain analytics
client.domains.getAnalytics("domain_id", "7d"); // period: "24h", "7d", "30d"

// Get domain stats
client.domains.getStats("domain_id", "2024-01-01", "2024-01-31");

Error Handling

The SDK provides robust error handling. By default, it throws UnsentException for non-200 responses.

Using Try-Catch

import dev.unsent.UnsentException;

try {
    client.emails.send(email);
} catch (UnsentException e) {
    System.out.println("Status: " + e.getStatusCode());
    System.out.println("Error: " + e.getError().get("message"));
}

Disable Exceptions

You can disable exceptions and check the success status manually:

// Initialize with raiseOnError = false
UnsentClient client = new UnsentClient("key", null, false);

UnsentResponse response = client.emails.send(email);

if (!response.isSuccess()) {
    System.out.println("Error: " + response.error);
}

Templates

Create and manage reusable email templates.

import dev.unsent.types.Types.CreateTemplateRequest;
import dev.unsent.types.Types.UpdateTemplateRequest;

// Create a template
CreateTemplateRequest template = new CreateTemplateRequest()
    .name("Welcome Email")
    .subject("Welcome to {{company}}")
    .html("<h1>Hello {{name}}!</h1><p>Welcome to our platform.</p>");

client.templates.create(template);

// List all templates
client.templates.list();

// Get a specific template
client.templates.get("template_id");

// Update a template
UpdateTemplateRequest update = new UpdateTemplateRequest()
    .name("Updated Welcome Email");

client.templates.update("template_id", update);

// Delete a template
client.templates.delete("template_id");

Suppressions

Manage your email suppression list to prevent sending to specific addresses.

import dev.unsent.types.Types.AddSuppressionRequest;

// Add an email to suppression list
AddSuppressionRequest suppression = new AddSuppressionRequest()
    .email("user@example.com")
    .reason("User requested to be removed");

client.suppressions.add(suppression);

// List all suppressions
client.suppressions.list();

// List with filters
client.suppressions.list(1, 20, "example.com", "bounce");

// Remove from suppression list
client.suppressions.delete("user@example.com");

Analytics & Metrics

Get insights into your email performance and account metrics.

Analytics

// Get overall analytics
client.analytics.get();

// Get time series analytics
client.analytics.getTimeSeries();

// Get reputation metrics
client.analytics.getReputation();

Metrics & Stats

// Get system metrics with optional period
client.metrics.get("7d"); // Options: "24h", "7d", "30d", "90d"

// Get stats for a date range
client.stats.get("2024-01-01", "2024-01-31");

// Get stats (defaults to all time)
client.stats.get();

Activity & Events

Track activity and email events across your account.

Activity Feed

// Get activity feed
client.activity.get();

// Get with pagination
client.activity.get(1, 20); // page, limit

Events

// List all email events
client.events.list();

// List with filters
client.events.list(1, 20, "delivered", "2024-01-01");
// Parameters: page, limit, status, startDate

Settings

Retrieve your account settings and configuration.

// Get account settings
client.settings.get();

API Keys

Programmatically manage your API keys.

import dev.unsent.types.Types.CreateApiKeyRequest;

// Create a new API key
CreateApiKeyRequest keyReq = new CreateApiKeyRequest()
    .name("Production Key");

client.apiKeys.create(keyReq);

// List all API keys
client.apiKeys.list();

// Delete an API key
client.apiKeys.delete("key_id");

System & Teams

Access system information and team management.

System

// Check API health status
client.system.health();

// Get API version
client.system.version();

Teams

// Get current team information
client.teams.get();

// List all teams (for multi-tenant accounts)
client.teams.list();

Webhooks

Set up webhooks to receive real-time notifications about email events.

import dev.unsent.types.Types.CreateWebhookRequest;
import dev.unsent.types.Types.UpdateWebhookRequest;
import java.net.URI;
import java.util.List;

// Create a webhook (simple method)
client.webhooks.create(
    "https://yourdomain.com/webhook", 
    List.of("email.sent", "email.delivered", "email.bounced")
);

// Or using detailed request object
CreateWebhookRequest webhook = new CreateWebhookRequest()
    .url(URI.create("https://yourdomain.com/webhook"))
    .eventTypes(List.of(
        CreateWebhookRequest.EventTypesEnum.EMAIL_SENT,
        CreateWebhookRequest.EventTypesEnum.EMAIL_DELIVERED,
        CreateWebhookRequest.EventTypesEnum.EMAIL_BOUNCED
    ));

client.webhooks.create(webhook);

// List all webhooks
client.webhooks.list();

// Get a specific webhook
client.webhooks.get("webhook_id");

// Update a webhook
UpdateWebhookRequest update = new UpdateWebhookRequest()
    .url(URI.create("https://yourdomain.com/new-webhook"))
    .eventTypes(List.of(UpdateWebhookRequest.EventTypesEnum.EMAIL_SENT));

client.webhooks.update("webhook_id", update);

// Test a webhook (sends a test event)
client.webhooks.test("webhook_id");

// Delete a webhook
client.webhooks.delete("webhook_id");

Resources