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.1</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;
UnsentClient client = new UnsentClient("un_xxx");Send an email
Now you are ready to send an email. You can do this by creating a map of email parameters and passing it to the client.emails.send method.
Here is an example of sending a simple HTML email:
import dev.unsent.UnsentClient;
import dev.unsent.UnsentClient.UnsentResponse;
import java.util.HashMap;
import java.util.Map;
// Initialize the client
UnsentClient client = new UnsentClient("un_xxx");
// Create the email parameters
Map<String, Object> email = new HashMap<>();
email.put("to", "user@example.com");
email.put("from", "no-reply@yourdomain.com");
email.put("subject", "Welcome");
email.put("html", "<strong>Hello!</strong>");
// Send the email
try {
UnsentResponse response = client.emails.send(email);
if (response.isSuccess()) {
System.out.println("Email sent! ID: " + response.data.get("id").getAsString());
} else {
System.err.println("Error: " + response.error.get("message").getAsString());
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}With attachments and scheduling
You can also send emails with attachments and schedule them to be sent at a later time.
- Attachments: specificy a list of maps, where each map contains
filenameandcontent(Base64 encoded string). - Scheduling: Use the
scheduledAtfield with an ISO 8601 formatted date string.
import java.util.List;
import java.util.ArrayList;
// Prepare the attachment
Map<String, Object> attachment = new HashMap<>();
attachment.put("filename", "report.txt");
attachment.put("content", "SGVsbG8gd29ybGQ="); // Content must be Base64 encoded
List<Map<String, Object>> attachments = new ArrayList<>();
attachments.add(attachment);
// Create the email with attachment and schedule
Map<String, Object> email = new HashMap<>();
email.put("to", "user@example.com");
email.put("from", "no-reply@yourdomain.com");
email.put("subject", "Report");
email.put("text", "See attached.");
email.put("attachments", attachments);
email.put("scheduledAt", "2024-12-01T10:00:00Z"); // Schedule for later
UnsentResponse response = client.emails.create(email);Batch send
To send multiple emails in a single API call, use the client.emails.batch method. This is more efficient for bulk sending.
List<Map<String, Object>> emails = new ArrayList<>();
// First email
Map<String, Object> email1 = new HashMap<>();
email1.put("to", "a@example.com");
email1.put("from", "no-reply@yourdomain.com");
email1.put("subject", "A");
email1.put("html", "<p>A</p>");
emails.add(email1);
// Second email
Map<String, Object> email2 = new HashMap<>();
email2.put("to", "b@example.com");
email2.put("from", "no-reply@yourdomain.com");
email2.put("subject", "B");
email2.put("html", "<p>B</p>");
emails.add(email2);
// Send batch
UnsentResponse response = client.emails.batch(emails);
if (response.isSuccess()) {
System.out.println("Sent batch emails");
}Idempotent Retries
To safely retry requests, you can pass an options map with an idempotencyKey.
Map<String, String> options = new HashMap<>();
options.put("idempotencyKey", "unique-key-123");
// For single email
client.emails.send(email, options);
// For batch emails
client.emails.batch(emails, options);Retrieve and manage emails
You can check the status of sent emails, update the scheduled time for pending emails, or cancel them.
Get an email
Retrieve the details and status of a specific email using its ID:
UnsentResponse response = client.emails.get("email_123");
if (response.isSuccess()) {
String status = response.data.get("status").getAsString();
System.out.println("Email status: " + status);
}Update schedule time
Change the scheduled time of a pending email:
Map<String, Object> update = new HashMap<>();
update.put("scheduledAt", "2024-12-01T11:00:00Z");
UnsentResponse response = client.emails.update("email_123", update);Cancel a scheduled email
Cancel a scheduled email before it gets sent:
UnsentResponse response = client.emails.cancel("email_123");
if (response.isSuccess()) {
System.out.println("Email cancelled successfully");
}Contacts
Manage your contacts and organize them into contact books.
Create a contact
Add a new contact to a specific contact book. You can also store custom metadata for each contact.
Map<String, Object> metadata = new HashMap<>();
metadata.put("plan", "pro");
Map<String, Object> contact = new HashMap<>();
contact.put("email", "user@example.com");
contact.put("firstName", "Jane");
contact.put("metadata", metadata);
UnsentResponse response = client.contacts.create("book_123", contact);Get a contact
Retrieve a contact's details using their ID and the contact book ID:
UnsentResponse response = client.contacts.get("book_123", "contact_456");Update a contact
Update a contact's information, such as their name or metadata:
Map<String, Object> update = new HashMap<>();
update.put("firstName", "John");
UnsentResponse response = client.contacts.update("book_123", "contact_456", update);Upsert a contact
Use upsert to create a contact if they don't exist, or update them if they do. This is useful for synchronization.
Map<String, Object> contact = new HashMap<>();
contact.put("email", "user@example.com");
contact.put("firstName", "Jane");
UnsentResponse response = client.contacts.upsert("book_123", "contact_456", contact);Delete a contact
Remove a contact from a book:
UnsentResponse response = client.contacts.delete("book_123", "contact_456");Campaigns
Campaigns allow you to send emails to all contacts in a specific contact book.
Create a campaign
Create a new campaign by defining its content and the target contact book.
Map<String, Object> campaign = new HashMap<>();
campaign.put("name", "Welcome Series");
campaign.put("subject", "Welcome!");
campaign.put("html", "<p>Thanks for joining us!</p>");
campaign.put("from", "welcome@yourdomain.com");
campaign.put("contactBookId", "book_123");
UnsentResponse response = client.campaigns.create(campaign);Schedule a campaign
Schedule the campaign to be sent at a specific date and time.
Map<String, Object> schedule = new HashMap<>();
schedule.put("scheduledAt", "2024-12-01T10:00:00Z");
UnsentResponse response = client.campaigns.schedule("campaign_123", schedule);Pause and resume campaigns
You can pause a running or scheduled campaign and resume it later.
// Pause
UnsentResponse pauseResp = client.campaigns.pause("campaign_123");
// Resume
UnsentResponse resumeResp = client.campaigns.resume("campaign_123");Domains
Manage the domains you use for sending emails.
List domains
Get a list of all your domains and their verification status.
UnsentResponse response = client.domains.list();
if (response.isSuccess()) {
// Process domains list
}Create a domain
Add a new domain to your account.
Map<String, Object> domain = new HashMap<>();
domain.put("domain", "yourdomain.com");
UnsentResponse response = client.domains.create(domain);Verify a domain
Check if a domain has been verified.
UnsentResponse response = client.domains.verify(123);
if (response.isSuccess()) {
String status = response.data.get("status").getAsString();
System.out.println("Verification status: " + status);
}Error handling
The SDK provides two ways to handle errors: throwing exceptions or checking the response object.
Using Exceptions (Default)
By default, the SDK throws an UnsentException if the API returns a non-2xx response.
import dev.unsent.UnsentException;
try {
UnsentResponse response = client.emails.get("email_123");
} catch (UnsentException e) {
System.err.println("API Error: " + e.getMessage());
System.err.println("Status Code: " + e.getStatusCode());
}Checking Response Object
If you prefer not to use exceptions for API errors, you can disable them during initialization. Then, check response.isSuccess() to determine if the request was successful.
// Initialize with raiseOnError = false
UnsentClient client = new UnsentClient("un_xxx", null, false);
UnsentResponse response = client.emails.get("email_123");
if (!response.isSuccess()) {
System.err.println("Error: " + response.error.get("message").getAsString());
}