Skip to content

Java SDK

A Java client for the API that does the encryption the Mailcycle apps do, on your machine. With it a program can create addresses that receive mail, open what arrives, and send. The recovery phrase never leaves the machine it runs on.

It needs Java 17 or later, and its one dependency is Jackson, for JSON. With Maven:

<dependency>
<groupId>email.mailcycle</groupId>
<artifactId>mailcycle</artifactId>
<version>0.5.1</version>
</dependency>

Or with Gradle:

implementation("email.mailcycle:mailcycle:0.5.1")

For a step-by-step tutorial with a Spring Boot controller, HTML, attachments and replies, see How to send email from Java on the Mailcycle Blog. To read an inbox, wait for mail and save attachments, see How to read email in Java.

Every call starts from the account’s twelve-word recovery phrase; there is no sign-up form. Make a free account at https://app.mailcycle.email/operator/signup (no card) and keep the twelve words it shows, or make one from Java:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;
import email.mailcycle.*;
public class MakeAccount {
public static void main(String[] args) throws Exception {
CreatedAccount created = Mailcycle.createAccount(null, Options.defaults());
// Nothing can recover the account without the phrase.
Path file = Files.createFile(Path.of("mailcycle-phrase.txt"),
PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")));
Files.writeString(file, created.phrase());
System.out.println(created.client().accountId());
}
}

Then put it in the environment, where the examples on this page read it:

Terminal window
export MAILCYCLE_PHRASE="$(cat mailcycle-phrase.txt)" # or paste the twelve words in quotes

Keep it out of your code and out of version control. If MAILCYCLE_PHRASE is not set, System.getenv returns null, so the program below checks it first and stops with MAILCYCLE_PHRASE is not set.

Save this as src/main/java/FirstMail.java in a Maven project with the dependency above, and run mvn -q compile exec:java -Dexec.mainClass=FirstMail:

import java.time.Duration;
import java.util.Objects;
import email.mailcycle.*;
public class FirstMail {
public static void main(String[] args) {
String phrase = Objects.requireNonNull(System.getenv("MAILCYCLE_PHRASE"), "MAILCYCLE_PHRASE is not set");
Mailcycle mc = Mailcycle.signIn(phrase, Options.defaults());
Address address = mc.addresses().create(new NewAddress().prefix("signup"));
System.out.println("Send an email to " + address.emailAddress());
Message message = mc.messages().waitFor(new WaitFor()
.addressId(address.id())
.timeout(Duration.ofMinutes(5)));
System.out.println(message.fromAddress() + " " + message.subject());
System.out.println(message.text());
}
}

Send it an email from any mailbox you use. waitFor returns it opened, usually a few seconds after you press Send. It waits 60 seconds unless timeout says otherwise, so this program gives you five minutes.

import email.mailcycle.*;
Mailcycle mc = Mailcycle.signIn(System.getenv("MAILCYCLE_PHRASE"), Options.defaults());

This is the same handshake the apps use: nothing secret crosses the wire, and it works on every plan.

With an API key instead, on Operator and up:

Mailcycle mc = Mailcycle.withApiKey(
System.getenv("MAILCYCLE_API_KEY"),
System.getenv("MAILCYCLE_PHRASE"), // null to manage without opening mail
Options.defaults());

Without the phrase a client can manage addresses, devices and metadata, but cannot open mail or create an address that receives it, because the address’s key is derived from the phrase. With both, the phrase is checked against the key’s account before anything is opened.

Each signIn opens a 30-day session. Keep mc.sessionToken() somewhere private and pick it up with Mailcycle.resume(token, phrase, options) rather than signing in on every run.

One account covers every device and agent you run. Make it once, then pair each device to it or give each one its own address, as Pair many devices shows. Paid plans pair as many devices as you have, and Fleet is built for device fleets at scale.

Address address = mc.addresses().create(new NewAddress()
.prefix("signup")
.label("Test run 42"));
List<Address> all = mc.addresses().list();

The public half of the address’s key goes up with the request so the mail server can seal what arrives; the private half stays on your machine. The label is sealed locally, and the server stores it as ciphertext.

With no prefix or localPart, the server rolls a name like quiet_falcon. Set style to choose the kind:

Address address = mc.addresses().create(new NewAddress().style(NameStyle.PERSON)); // maya.holt

The styles are PERSON, BUSINESS, TEAM and NEUTRAL, the default. style is ignored when prefix or localPart is set.

To pick a name before creating, roll a few:

List<String> names = mc.addresses().rollNames(NameStyle.BUSINESS, null); // up to 8, like harbor-supply42
Address address = mc.addresses().create(new NewAddress().localPart(names.get(0)));

A rolled name works as localPart on every plan; any other name needs Scale and up. The names are free when rolled, but someone can take one before you create it, and then create is refused. Pass a domain as the second argument to roll for it; null uses the one create would.

AddressKeyExport key = mc.addresses().exportKey(address.id()); // the current epoch
AddressKeyExport old = mc.addresses().exportKey(address.id(), 0); // an earlier epoch
System.out.println(key.privateKey() + " " + key.publicKey()); // base64url
RotatedKey rotated = mc.addresses().rotateKey(address.id()); // now on epoch + 1

exportKey returns one address’s private key (base64url) and public key at a key epoch, to hand to a helper that reads that one address’s mail, such as the decrypt Worker. The epoch runs from 0 to the address’s current one (invalid_epoch otherwise). The export is recorded in the account history before the key is derived. The key is derived on your machine. It needs the phrase and a signed-in session, and the key opens that address’s mail and nothing else, so treat it like the mail itself.

rotateKey moves the address to its next key epoch, so an exported key stops opening new mail. A device or agent holding the address is handed the new key. An address shared with team members is refused with team_address: rotate it in the web app, which also gives each member the new key.

List<Message> messages = mc.messages().all(address.id(), null);
for (Message message : messages) {
System.out.println(message.fromAddress() + " " + message.subject());
}
byte[] data = mc.messages().attachment(messages.get(0), 0); // opened locally

A message that will not open, because there is no phrase or it is the wrong one, comes back with opened() false and empty content rather than an exception, so one unreadable message does not hide the rest of a page.

message.html() is the HTML as the sender wrote it. message.safeHtml() has every remote image, stylesheet and embed removed, as the apps do it, and is the one to render; message.blocked() lists what was taken out.

Message code = mc.messages().waitFor(new WaitFor()
.addressId(address.id())
.subject("verification"));

Listens on the event stream where it is available and polls the address otherwise, and returns the message opened. If nothing matching arrives in time it throws an ApiException with code() timeout. Mail received from since on counts, even if it landed before the stream was up; it defaults to now, so to wait for a reply to something you are about to send, take the time before sending.

mc.messages().send(new Outgoing(address.emailAddress(), "someone@example.com", "Hello", "Hi"));

Call .replyTo(message) on the Outgoing with the message you are answering to thread a reply. A session can send from Personal up; an API key on Scale and up. Free receives only.

send returns a SendResult: messageId() is the Message-ID header, and sentCopyId() is the id of the copy in Sent, which the other message calls take, or null when the address keeps none.

Attachments take raw bytes and the client encodes them. A message can carry up to ten files, 3.5 MB between them. Give a file a contentId to show it inline, where the HTML says cid: and that id. Program and script files, like .exe and .js, are refused.

byte[] pdf = Files.readAllBytes(Path.of("invoice.pdf"));
byte[] logo = Files.readAllBytes(Path.of("logo.png"));
mc.messages().send(new Outgoing(address.emailAddress(), "someone@example.com", "Your invoice", "Attached.")
.html("<img src=\"cid:logo\"><p>Attached.</p>")
.attachments(List.of(
new OutgoingAttachment("invoice.pdf", pdf).mimeType("application/pdf"),
new OutgoingAttachment("logo.png", logo).mimeType("image/png").contentId("logo"))));
try (EventStream stream = mc.events().stream()) {
for (AccountEvent event; (event = stream.nextEvent(null)) != null; ) {
System.out.println(event.type());
}
}

Events carry ids, never content, and are not replayed after a drop, so Hooks.onReconnect, passed to streamWith(hooks), is where to refetch what you are showing. nextEvent(null) waits as long as it takes and returns null once the stream is closed; pass a Duration to read one event with a deadline.

To check a webhook came from Mailcycle, pass the body exactly as it arrived:

boolean genuine = WebhookSignature.verifyNow(secret, rawBody, header);
CreatedApiKey created = mc.apiKeys().create("Deploy script");
System.out.println(created.token()); // shown once; keep it somewhere private
for (ApiKey key : mc.apiKeys().list()) {
System.out.println(key.id() + " " + key.name() + " ..." + key.hint());
}
mc.apiKeys().revoke(created.apiKey().id());

Listing, creating and revoking keys need a signed-in session, so a leaked key cannot make more of itself. The name is sealed on your machine, and the server stores it as ciphertext. A name that will not open comes back as null.

signOut() on a client built with an API key does nothing. A key is not a session; it works until it is revoked.

CreatedWebhook created = mc.webhooks().create(
"https://example.com/hooks/mail", List.of("message.received"), "Orders");
String secret = created.secret(); // shown once, for checking signatures
mc.webhooks().update(created.webhook().id(), new WebhookUpdate().enabled(false));
mc.webhooks().test(created.webhook().id());
DeliveryPage page = mc.webhooks().deliveries(created.webhook().id(), null, null);
for (WebhookDelivery delivery : page.deliveries()) {
System.out.println(delivery.eventType() + " " + delivery.status() + " " + delivery.responseStatus());
}

Webhooks are on Operator and up. list() returns the webhooks with their names opened, and every event type one can ask for. rotateSecret returns a new secret once, and redeliver sends a logged event again with the same event id. Adding, changing, rotating and removing need a signed-in session; an API key can list, test, read deliveries and redeliver.

for (Session session : mc.sessions().list()) {
System.out.println(session.id() + " " + session.expiresAt() + " " + session.current());
}
mc.sessions().revokeOthers();

revoke(id) ends one session. All three need a signed-in session.

mc.deleteAccount();

Erases the account and everything in it at once, with no grace period. Its addresses are retired and never issued again. It needs a signed-in session. If the account balance still holds money you paid in, it is refused with balance_held: ask for the balance back through support first.

mc.subscription() returns the plan, renewal date and balance, and mc.plans() lists every plan.

// The text of the device's QR code, or the eight digits it shows.
Device device = mc.devices().pair("MC1:12345678:...", "Kitchen Pi");
mc.devices().assign(device.id(), address.id()); // hands the keys over too
mc.devices().unassign(device.id(), address.id());
mc.devices().handOverKeys(device.id()); // again, on its own

This is what the app’s Add device screen does, done by a script. It needs the phrase and a signed-in session. The name is sealed on your machine.

Each device has a wrap secret, and its address keys are sealed under it. The account keeps a copy in the device’s sealed profile, so keys can be handed over again when an address is assigned or taken off.

There are two ways the secret gets here. The QR code carries the device’s own secret, so it never passes through Mailcycle. The eight digits carry no secret, so the client makes one and seals it to a key the device published. The server relays that key, so it could put its own in its place at pairing and read the keys that follow. The QR path does not have that gap. Use it where you can.

A device on an older build publishes no key. Pairing it by its digits fails with an error that says to pair it in the app, or pass its QR code instead.

Everything throws MailcycleException, which is unchecked. An API failure is an ApiException carrying the HTTP status() and the API’s own code in code(), which is what to match on rather than the message.

When the account’s plan does not include a call (plan_required or plan_capability_required), the error also carries requiredPlanId(), the lowest plan that allows it, and upgradeUrl(), the page that moves the account to that plan. getMessage() ends with the link:

plan_required: API keys need the Operator plan or higher. Upgrade at https://app.mailcycle.email/operator/billing?upgrade=plan_operator

It is checked against the published test vectors, including the refusals. The cryptography itself is the JDK’s: X25519, ChaCha20, HMAC-SHA256 and PBKDF2.

© Northlab Studios Ltd, trading as Mailcycle. Registered in England and Wales, company no. 17462734. Registered office: 167-169 Great Portland Street, London W1W 5PF.