How to Read Email in Java: Read the Inbox, Save Attachments and Receive Mail in Spring Boot
Read email in Java without IMAP: a complete program that lists an inbox and opens the newest message, then attachments, waits and Spring Boot webhooks.

You want to read email in Java: read a supplier’s invoice and save the PDF, pick a sign-in code out of a verification email in a test, or hand a customer’s reply to your Spring Boot service. Jakarta Mail (the successor to JavaMail) has a Store and Folder API for reading mail, but it needs an IMAP or POP3 mailbox, its host, port and password, and then a walk through the MIME parts. If what you want is “give my program an address and let it read what arrives”, an email API is shorter.
This tutorial shows how to read and receive email in Java with the Mailcycle Java SDK, the email.mailcycle:mailcycle library. You’ll start with a complete Java program that reads an inbox, then create an address, list and open messages, save attachments to disk, wait for the next email, and then get new mail pushed to a Spring Boot controller by webhook.
It is the reading half of How to send email from Java, which opens with a plain Java program that sends email and covers HTML, attachments you send and threaded replies. This one goes deep on the inbox.
Quick answer: how to read email in Java
Add the library, sign in with your recovery phrase, find the address you want to read, and list its inbox. Every message comes back parsed and decrypted, with the sender, subject, text, HTML and attachments as record components.
dependencies {
implementation 'email.mailcycle:mailcycle:0.5.1'
}
Read email in Java: a complete program
This is the whole program. It takes the address to read as its argument, prints the ten newest messages in the inbox with a * beside the unread ones, then prints the newest message in full and marks it read.
import email.mailcycle.Address;
import email.mailcycle.Mailcycle;
import email.mailcycle.Message;
import email.mailcycle.MessagePage;
import email.mailcycle.Options;
public class ReadEmail {
public static void main(String[] args) {
Mailcycle mc = Mailcycle.signIn(System.getenv("MAILCYCLE_PHRASE"), Options.defaults());
String email = args[0]; // the inbox to read, an address on your account
Address inbox = mc.addresses().list().stream()
.filter(a -> a.emailAddress().equalsIgnoreCase(email))
.findFirst()
.orElseThrow(() -> new IllegalStateException(email + " is not on this account"));
MessagePage page = mc.messages().list(inbox.id(), "inbox", 10, null);
for (Message message : page.messages()) {
String unread = message.read() ? " " : "*";
System.out.println(unread + " " + message.receivedAt() + " " + message.fromAddress() + " " + message.subject());
}
if (!page.messages().isEmpty()) {
Message newest = page.messages().get(0);
System.out.println();
System.out.println("From: " + newest.fromName() + " <" + newest.fromAddress() + ">");
System.out.println("Subject: " + newest.subject());
System.out.println(newest.text());
System.out.println(newest.attachments().size() + " attachment(s)");
mc.messages().markRead(newest.id(), true);
}
}
}
We ran it against SDK 0.5.1 from Maven Central. Its output looks like this, with the newest message first:
* 2026-11-29T21:52:23.380Z support-s3qx@letterhold.com Hello from Java
* 2026-11-27T14:52:11.871Z support-s3qx@letterhold.com Re: [T-1] Cannot log in
From: Acme Notifications <support-s3qx@letterhold.com>
Subject: Hello from Java
Hi,
This email was sent from a plain Java program with the Mailcycle SDK.
0 attachment(s)
Compile and run it with javac
From an IDE with the Gradle or Maven dependency, run the class and pass the address as a program argument. With no build tool, put four jars in a lib folder: mailcycle-0.5.1.jar and the jackson-databind, jackson-core and jackson-annotations jars it depends on, all on Maven Central. Then:
export MAILCYCLE_PHRASE="your twelve words ..."
javac -cp 'lib/*' ReadEmail.java
java -cp 'lib/*:.' ReadEmail invoices-x7k2@example-pool.email
On Windows, the class path separator is ;, so the last line is java -cp "lib/*;." ReadEmail .... The program reads over HTTPS, so there is no IMAP host or port to open in a firewall.
Receive the next email instead
To have the program wait for new mail rather than read what is already there, create an address and call waitFor. It returns when a message arrives, opened.
import email.mailcycle.*;
import java.time.Duration;
public class ReceiveEmail {
public static void main(String[] args) {
Mailcycle mc = Mailcycle.signIn(System.getenv("MAILCYCLE_PHRASE"), Options.defaults());
Address address = mc.addresses().create(new NewAddress().prefix("inbound").label("Java inbox"));
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());
}
}
Run it, send an email to the address it prints from any mail app, and the program prints what you sent. The rest of this guide is what a real service needs around these two programs: paging, attachments, push and errors.
Prerequisites
- Java 17 or later. Check with
java -version. The same dependency works from Kotlin and Scala. - A Mailcycle account. Receiving works on every plan when your program signs in with the recovery phrase. API keys and webhooks start at Operator. Pricing has the plans.
- Your recovery phrase, in an environment variable named
MAILCYCLE_PHRASE, for any process that opens mail.
Step 1: Add the dependency
With Maven:
<dependency>
<groupId>email.mailcycle</groupId>
<artifactId>mailcycle</artifactId>
<version>0.5.1</version>
</dependency>
Everything you need is in the email.mailcycle package. Its one dependency is Jackson. The handles you use are mc.addresses(), mc.messages() and mc.webhooks(), and every call throws an unchecked MailcycleException, so there are no throws clauses to thread through your code.
Step 2: Sign in and create an address
Mailcycle.signIn(phrase, Options.defaults()) works on every plan. Each sign-in opens a 30-day session, so a program that runs often can keep mc.sessionToken() and pick it up again with Mailcycle.resume(token, phrase, Options.defaults()).
An address that receives mail needs a public key the mail server can encrypt to. addresses().create() derives that key from your phrase and uploads only the public half.
Address address = mc.addresses().create(
new NewAddress().prefix("invoices").label("Supplier invoices").retentionDays(30));
System.out.println(address.emailAddress() + " " + address.id());
for (Address existing : mc.addresses().list()) {
System.out.println(existing.emailAddress() + " " + existing.label() + " " + existing.receives());
}
The options on NewAddress:
prefix("invoices")givesinvoices-plus a random ending on a shared domain.style(NameStyle.PERSON)rolls a name in that style (alsoBUSINESS,TEAMandNEUTRAL), andmc.addresses().rollNames(style, null)lists free ones.localPartasks for an exact name. Any name you type needs Scale or above, and so doesdomainwith your own domain.labelis encrypted on your machine, so the server stores it as ciphertext.retentionDaysis 1 to 90, and 7 when left out.
Save address.id(), the ibx_... id: every reading call takes it.
Step 3: List and read emails in the inbox
messages().list returns one page of a folder, newest first:
MessagePage page = mc.messages().list(address.id(), "inbox", 20, null);
for (Message message : page.messages()) {
String flag = message.read() ? " " : "*";
System.out.println(flag + " " + message.receivedAt() + " " + message.fromAddress() + " " + message.subject());
}
if (page.nextCursor() != null) {
MessagePage older = mc.messages().list(address.id(), "inbox", 20, page.nextCursor());
System.out.println(older.messages().size() + " older messages on the next page");
}
The folder, the limit and the cursor can each be null to take the default. nextCursor() is opaque: pass it back as it came, and it is null on the last page. To walk a whole folder, all pages for you:
List<Message> all = mc.messages().all(address.id(), "inbox");
List<Message> invoices = all.stream()
.filter(m -> m.subject().toLowerCase().contains("invoice") && !m.attachments().isEmpty())
.toList();
System.out.println(invoices.size() + " invoices with files attached");
Message content is encrypted, so you decrypt and then filter in Java, as above. Pass "sent", "junk", "trash" or "starred" as the folder to read another one.
What is in a Message
Each Message is a record, already parsed from MIME and decrypted:
| Component | What it holds |
|---|---|
id(), addressId() |
The message’s msg_... id and the address it arrived at. |
receivedAt() |
When it arrived, as an RFC 3339 string in UTC. |
fromAddress(), fromName() |
The sender’s address and display name. |
replyTo() |
Where a reply should go: the Reply-To header if set, otherwise From. |
to(), subject() |
The recipient and the subject line. |
text() |
The plain-text body. |
html() |
The HTML body exactly as sent. Do not render this one. |
safeHtml() |
The HTML with remote images, trackers and embeds removed. |
attachments() |
A list of Attachment: index(), filename(), mimeType(), size(), contentId(), stored(). |
messageId() |
The sender’s Message-ID header, used to thread a reply. |
read(), starred(), folder() |
The message’s state. |
opened() |
false if it could not be decrypted: no phrase, or the wrong one. |
A message that does not open comes back with opened() set to false and empty content rather than an error, so one bad message never hides the rest of a page.
Read the email body in Java: text, HTML and safeHtml
Most mail carries a plain-text and an HTML part. Use text() for anything you parse, such as codes, order numbers or a reply to hand to a model. If you show the HTML anywhere, use safeHtml():
Message message = mc.messages().get("msg_91be02c4a7d1");
if (!message.opened()) {
throw new IllegalStateException("this message did not open: check the recovery phrase");
}
System.out.println(message.text().isEmpty() ? "(no plain-text part)" : message.text());
if (!message.safeHtml().isEmpty()) {
Files.writeString(Path.of("preview.html"), message.safeHtml());
System.out.println(message.blocked().size() + " remote items taken out");
}
get fetches one message by id, from any folder. safeHtml() is the HTML the Mailcycle apps show: remote images, tracking pixels and embeds are taken out, so opening it does not tell the sender when you read it. If you embed it in a page of your own, put it in a sandboxed <iframe>.
Download email attachments in Java
Attachments are listed on the message and fetched one at a time. Their bodies are encrypted like the message, and attachment opens them on your machine. This method saves a message’s files safely:
static List<Path> saveAttachments(Mailcycle mc, Message message, Path folder) throws IOException {
Path target = folder.resolve(message.id());
List<Path> saved = new ArrayList<>();
for (Attachment attachment : message.attachments()) {
if (!attachment.stored()) {
continue; // an empty part: nothing to fetch
}
if (attachment.contentId() != null && !attachment.contentId().isEmpty()) {
continue; // an image the HTML shows inline, like a logo
}
byte[] data = mc.messages().attachment(message, attachment.index()); // opened on this machine
Files.createDirectories(target);
Path fileName = Path.of(attachment.filename().replace('\\', '/')).getFileName();
String name = fileName == null || fileName.toString().isEmpty() ? "attachment" : fileName.toString();
Path path = target.resolve(attachment.index() + "-" + name);
Files.write(path, data);
saved.add(path);
}
return saved;
}
Then process every unread message that has files, and mark each one read so the next run skips it:
for (Message message : mc.messages().all(address.id(), "inbox")) {
if (message.read() || message.attachments().isEmpty()) {
continue;
}
for (Path path : saveAttachments(mc, message, Path.of("downloads"))) {
System.out.println("saved " + path);
}
mc.messages().markRead(message.id(), true);
}
The details that matter with real mail:
- The file name comes from the sender. A name like
../../.bashrcis a classic path-traversal trick.getFileName()keeps the last path component, and the index prefix keeps two files calledinvoice.pdfapart. stored()isfalsefor a part that had no body. Skip it.contentId()marks an inline image, the kind HTML shows with<img src="cid:logo">. Most pipelines want the PDF, not the logo.mimeType()andsize()let you keep onlyapplication/pdf, or refuse anything over a size, before you download it.- Treat files as untrusted. Scan them, or open them in a sandbox, before anything else touches them.
That is the job a Java email parser does for attachments, without walking a Multipart tree or decoding base64.
Wait for the next email in Java
waitFor returns when a matching message arrives, opened. It is the shortest way to read a verification email in an end-to-end test, or to wait for a reply:
Instant started = Instant.now(); // take the time before the email is triggered
// ...trigger the email here: submit a sign-up form, call your own API...
try {
Message message = mc.messages().waitFor(new WaitFor()
.addressId(address.id())
.subject("verify")
.since(started)
.timeout(Duration.ofMinutes(2)));
Matcher code = Pattern.compile("\\b(\\d{6})\\b").matcher(message.text());
if (!code.find()) {
throw new IllegalStateException("no code in: " + message.text());
}
System.out.println("code: " + code.group(1));
} catch (ApiException e) {
if (e.code().equals("timeout")) {
throw new IllegalStateException("no verification email within two minutes", e);
}
throw e;
}
How it behaves:
sinceis the important one. Mail received from that moment on counts, even if it landed before the wait began. Take the time before you trigger the email, so a fast delivery cannot slip past. It defaults to whenwaitForis called.fromandsubjectmatch text the sender or subject contains, ignoring case.addressIdlimits the wait to one address.timeoutis 60 seconds by default. When it runs out you get anApiExceptionwhosecode()is"timeout".pollEvery(five seconds by default) is how often it checks when the live stream is not available.
In a JUnit 5 test, create the address in a @BeforeEach and delete it afterwards:
class SignupEmailTest {
static final Mailcycle mc = Mailcycle.signIn(System.getenv("MAILCYCLE_PHRASE"), Options.defaults());
Address address;
@BeforeEach
void createAddress() {
address = mc.addresses().create(new NewAddress().prefix("test").retentionDays(1));
}
@AfterEach
void deleteAddress() {
mc.addresses().delete(address.id());
}
}
Mark as read, star, move and delete
These calls change state only, so they do not open any content:
| Call | What it does |
|---|---|
mc.messages().markRead(id, true) |
Marks read. markRead(id, false) marks unread. |
mc.messages().star(id, true) |
Stars it. star(id, false) unstars. |
mc.messages().moveTo(id, "junk") |
Moves to "inbox", "junk" or "trash". |
mc.messages().delete(id) |
Deletes it now. |
Get new email pushed to Spring Boot with a webhook
Mailcycle can tell your service the moment mail arrives. A message.received event carries the message’s id and its address’s id. Your code fetches the message by id and opens it locally, so the phrase stays on your machine.
Add a webhook in the app under API, on the Webhooks tab, or from Java with a signed-in session:
CreatedWebhook created = mc.webhooks().create(
"https://example.com/hooks/mailcycle", List.of("message.received"), "Inbound mail");
System.out.println(created.webhook().id() + " " + created.secret()); // whsec_..., shown once: store it
The URL must be HTTPS. For local development, expose your dev server through a tunnel. First the client as a singleton bean, then the controller:
@Configuration
public class MailcycleConfig {
@Bean
public Mailcycle mailcycle(@Value("${mailcycle.phrase}") String phrase) {
// One client for the whole application. It is safe to share between threads.
return Mailcycle.signIn(phrase, Options.defaults());
}
}
@RestController
public class InboundMailController {
private final Mailcycle mc;
private final String secret;
private final ExecutorService worker = Executors.newFixedThreadPool(4);
private final Set<String> seen = ConcurrentHashMap.newKeySet(); // one instance only: use a table with a unique key in production
private final ObjectMapper json = new ObjectMapper();
public InboundMailController(Mailcycle mc, @Value("${mailcycle.webhook-secret}") String secret) {
this.mc = mc;
this.secret = secret;
}
@PostMapping("/hooks/mailcycle")
public ResponseEntity<Void> receive(
@RequestBody byte[] raw, // the exact body, before any parsing
@RequestHeader(value = "Mailcycle-Signature", required = false) String signature,
@RequestHeader(value = "Mailcycle-Event-Id", required = false) String eventId) throws IOException {
if (!WebhookSignature.verifyNow(secret, raw, signature)) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
if (eventId != null && !seen.add(eventId)) {
return ResponseEntity.noContent().build(); // a retry of an event already handled
}
JsonNode event = json.readTree(raw);
if (event.path("type").asText().equals("message.received")) {
String messageId = event.path("payload").path("messageId").asText();
worker.submit(() -> process(messageId)); // answer fast, then do the work
}
return ResponseEntity.noContent().build();
}
private void process(String messageId) {
Message message = mc.messages().get(messageId); // fetched by id, opened here
if (!message.opened()) {
return;
}
try {
List<Path> saved = saveAttachments(mc, message, Path.of("downloads"));
System.out.printf("%s: %s (%d files)%n", message.fromAddress(), message.subject(), saved.size());
} catch (IOException e) {
System.err.println("could not save files for " + messageId + ": " + e.getMessage());
}
mc.messages().markRead(message.id(), true);
}
}
saveAttachments is the method from the attachments section. What each part is for:
- The signature is an HMAC-SHA256 of the timestamp and the raw body, keyed with your
whsec_secret.WebhookSignature.verifyNowchecks it in constant time and refuses a timestamp more than five minutes old. Take the body asbyte[]: a body that was decoded and re-encoded will not match. - Answer fast. Mailcycle waits 10 seconds for a
2xx. The controller replies first and does the fetching and saving on a worker thread. - Deduplicate. An event can arrive more than once, and
Mailcycle-Event-Idis the same on every attempt. The in-memory set suits one instance. With several, insert the id into a table with a unique constraint. - Quarkus, Micronaut and Javalin follow the same steps: read the raw body, verify, fetch by id.
You can test the controller without a live webhook. WebhookSignature.header(secret, body, timestamp) builds the header Mailcycle would send. Retries, the delivery log and every event type are in the webhooks guide, and Receive email with a webhook walks through the receiver in more depth.
An IMAP client and an email API in Java
Jakarta Mail reads a mailbox through Session, Store and Folder: you give it a host, port 993 and credentials, open INBOX, fetch each MimeMessage and walk its Multipart to find the body and the files.
The Mailcycle Java SDK is built for programs that need addresses of their own: one per customer, per test run or per agent, created in code, with mail pushed to you as it arrives.
| Jakarta Mail with IMAP | Mailcycle Java SDK | |
|---|---|---|
| Install | jakarta.mail and an implementation |
email.mailcycle:mailcycle |
| You need | An IMAP mailbox and its credentials | A recovery phrase, plus an API key if you want one |
| New addresses | Made at your mail provider | mc.addresses().create() in code |
| Parsing | MimeMessage and Multipart, walked by you |
Parsed fields: text(), html(), attachments() |
| Tracker-free HTML | Strip it yourself | safeHtml(), with blocked() listing what was removed |
| Attachments | Walk the BodyParts |
mc.messages().attachment(message, index) |
| New-mail push | IMAP IDLE | Webhooks and mc.events().stream() |
| Wait for one email | Write the loop yourself | waitFor() |
| Mail at rest | Depends on the provider | Encrypted with keys from your recovery phrase |
Wire the client as a Spring bean
In a Spring Boot service, sign in once and share the client. A @Configuration class builds the bean from properties, so controllers and schedulers take it by constructor injection.
@Configuration
class MailcycleConfig {
@Bean
Mailcycle mailcycle(@Value("${mailcycle.phrase}") String phrase) {
return Mailcycle.signIn(phrase, Options.defaults());
}
}
@Component
class InvoicePoller {
private final Mailcycle mc;
private final String addressId;
InvoicePoller(Mailcycle mc, @Value("${mailcycle.invoice-address-id}") String addressId) {
this.mc = mc;
this.addressId = addressId;
}
@Scheduled(fixedDelay = 60_000)
void poll() {
for (Message message : mc.messages().all(addressId, "inbox")) {
if (message.read()) {
continue;
}
handle(message);
mc.messages().markRead(message.id(), true);
}
}
}
Set mailcycle.phrase from an environment variable or your secret manager, and never from application.properties in version control. @Scheduled runs on a single thread by default, so a slow handler delays the next poll; for a busy inbox prefer a webhook, as shown earlier.
A JUnit 5 extension for test addresses
JUnit 5 lets you package setup and teardown as an extension, so every test class that needs an inbox shares one piece of code. Implement BeforeEachCallback and AfterEachCallback, store the address in the extension context and resolve it as a parameter.
class InboxExtension implements BeforeEachCallback, AfterEachCallback, ParameterResolver {
private static final Mailcycle MC = Mailcycle.signIn(System.getenv("MAILCYCLE_PHRASE"), Options.defaults());
private Address address;
public void beforeEach(ExtensionContext ctx) {
address = MC.addresses().create(new NewAddress().prefix("junit").retentionDays(1));
}
public void afterEach(ExtensionContext ctx) { MC.addresses().delete(address.id()); }
public boolean supportsParameter(ParameterContext p, ExtensionContext c) { return p.getParameter().getType() == Address.class; }
public Object resolveParameter(ParameterContext p, ExtensionContext c) { return address; }
}
A test then declares @ExtendWith(InboxExtension.class) and takes an Address argument. The extension also works from @SpringBootTest, so the same address can be the user’s email in a MockMvc sign-up request.
Wait on several addresses with CompletableFuture
The waitFor call blocks, so run several at once on an executor. CompletableFuture.supplyAsync(() -> mc.messages().waitFor(...), pool) for each address, then CompletableFuture.allOf(...).join(). Size the pool to the number of waits and give every wait its own timeout, so one slow message does not hold up the rest.
Virtual threads for blocking waits
waitFor blocks the calling thread until a message arrives, which is simple but costly on platform threads when many waits run at once. On Java 21 and later, run each wait on a virtual thread, so thousands can be parked cheaply while they listen.
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
List<Future<Message>> waits = addresses.stream()
.map(a -> executor.submit(() -> mc.messages().waitFor(
new WaitFor().addressId(a.id()).subject("verify").timeout(Duration.ofMinutes(1)))))
.toList();
for (Future<Message> wait : waits) {
System.out.println(wait.get().subject());
}
}
The SDK needs Java 17 or later, so on 17 use a fixed thread pool sized to the number of waits instead. Either way, give every wait its own timeout and handle ApiException with the timeout code per future, so one quiet address does not fail the whole batch.
Testing a Spring controller with MockMvc
In a @SpringBootTest, create the address in a @BeforeEach, post the sign-up with MockMvc using address.emailAddress(), and wait for the message with waitFor before asserting on its text. Because the whole Spring context runs in the test, the email goes out through the real mail sender configured for the test profile. Use a separate Spring profile for this, with a provider that delivers to outside addresses, and keep the profile out of the default build so the suite stays fast offline.
Troubleshooting
- Two threads sign in at once. Share one
Mailcycleinstance as a Spring bean, and keep the phrase in your secret manager rather thanapplication.properties. - Callers each repeat the timeout check. Catch
ApiExceptiononce at the edge of your service and turn thetimeoutcode into a normal result. - Messages have
opened()set tofalseand empty fields. The client has no phrase, or a phrase from a different account. Build it withMailcycle.signIn(phrase, ...). - Nothing arrives at a new address. Check
address.receives()inmc.addresses().list(), and check the sender used the exact address, since prefixed names have a random ending. e.code()israte_limited. You are reading too much too fast. Back off, read only what is new, or switch to webhooks.- A 404 fetching an attachment. The part has
stored()set tofalse. Skip it. - The webhook controller returns 401 for real deliveries. You are verifying a re-encoded body, or the wrong secret. Take the body as
byte[]and use thewhsec_secret of this webhook.
Every error code is listed in Errors.
Reply from Java, or hand the inbox to an agent
To answer a message in the same thread, call .replyTo(message) on an Outgoing and send it with mc.messages().send(). Sending email from Java covers that, along with the plans that send.
If an AI agent should read the inbox, Mailcycle also runs as an MCP server with tools such as wait_for_message, read_message and read_attachment, for Claude Code, Cursor, Codex or any other MCP client. Start with Give your AI agent its own email inbox.
Next steps
- Read the Java SDK page and the full Java SDK guide, and Reading mail for folders, paging and attachments at the API level.
- See Encryption and sealed data and the security page.
- Send as well as receive with How to send email from Java, or the same flow in another language.
- Everything for developers is on the developers page, and the plans are on pricing.
FAQ
How do I read email in Java?
Sign in with Mailcycle.signIn(phrase, Options.defaults()), find the address with mc.addresses().list(), and call mc.messages().list(address.id(), "inbox", 10, null). Each Message in the page is already parsed and decrypted, so fromAddress(), subject(), text() and attachments() are ready to use. The complete ReadEmail program is at the top of this guide.
Is there a Java email client library for reading mail in code?
Yes. The Mailcycle Java SDK, email.mailcycle:mailcycle on Maven Central, is a Java email client for programs: it reads, waits for, stars, moves and deletes mail over HTTPS, downloads attachments and sends replies. It needs Java 17 or later and depends only on Jackson, and it is Apache-2.0 licensed.
How do I read only unread emails in Java?
Each Message has read(). Walk the inbox with mc.messages().all(addressId, "inbox"), skip messages where read() is true, handle the rest, and call mc.messages().markRead(id, true) so the next run skips them too.
How do I compile and run a Java program that reads email?
With Maven or Gradle, add email.mailcycle:mailcycle:0.5.1 and run the class from your IDE. With plain javac, put the SDK jar and its three Jackson jars in a lib folder, then run javac -cp 'lib/*' ReadEmail.java and java -cp 'lib/*:.' ReadEmail followed by the address to read, with MAILCYCLE_PHRASE set in the environment.
How do I receive email in Java?
Give your program an address that receives mail, then read it with a client. With Mailcycle, add email.mailcycle:mailcycle, sign in with Mailcycle.signIn(phrase, Options.defaults()), create an address with mc.addresses().create(new NewAddress()), and call mc.messages().waitFor(new WaitFor()). The Message comes back parsed and decrypted: sender, subject, text, HTML and attachments.
How do I read emails from an inbox in Java?
Call mc.messages().list(addressId, null, 20, null) for one page, newest first, or mc.messages().all(addressId, "inbox") to walk the whole folder. Each Message is a record with fromAddress(), subject(), text(), safeHtml(), attachments() and read().
How do I download email attachments in Java?
Each Message lists its files in attachments(), with filename(), mimeType(), size() and index(). Call mc.messages().attachment(message, attachment.index()) to get a byte[], opened on your machine, and write it with Files.write. Clean the file name first with Path.of(name).getFileName(), because it comes from the sender.
How can a Java program wait for a new email?
Call mc.messages().waitFor(new WaitFor().addressId(...).subject(...).since(...).timeout(...)). It returns the first matching message. If nothing matches in time it throws an ApiException whose code() is timeout.
How do I get notified when an email arrives in a Spring Boot app?
Add a webhook for message.received, point it at a @RestController, and check each delivery with WebhookSignature.verifyNow() against the raw body. The event carries the message id, so fetch the message with mc.messages().get(). Webhooks are on the Operator plan and above.
Is there a Java library to read email without IMAP?
Yes. The Mailcycle Java SDK reads mail over HTTPS, so there is no IMAP host, port or mailbox password, and the message arrives already parsed.
Which Mailcycle plan do I need to receive email from Java?
Every plan can create addresses, read mail and download attachments when the program signs in with the recovery phrase. API keys and webhooks start at Operator. See Plans and limits.
Why does the Java client need my recovery phrase?
Mail is encrypted the moment it arrives, with keys from your recovery phrase. The Java client derives the same keys on your machine and opens each message in your process. A message that does not open comes back with opened() set to false.
Related
Receive email in code
- AgentMail Alternative for AI Agent Inboxes (AgentMail alternative)
- CloudMailin Alternative: Inbound Email to Rails With an Address per API Call (CloudMailin alternative)
- Mailgun Inbound Routes Alternative: Route Mail by Address, Not Regex (Mailgun Routes alternative)
- Mailosaur Alternative for Email Testing and Test Inboxes (Mailosaur alternative)
- Mailparser and Parseur Alternative: Incoming Email as JSON on a Webhook (Mailparser and Parseur alternative)
- MailSlurp Alternative for Email Testing and Test Inboxes (MailSlurp alternative)
- Mailtrap Alternative for Email Testing and Test Inboxes (Mailtrap alternative)
- Postmark Inbound Alternative: Addresses by API, Signed Webhooks (Postmark inbound alternative)
- Resend Inbound Alternative: An Address per API Call, Signed Events (Resend inbound alternative)
- SendGrid Inbound Parse Alternative: Inbound Email by API Call (SendGrid Inbound Parse alternative)
- Testmail.app Alternative for Email Testing and Test Inboxes (Testmail.app alternative)
- Test Email Flows on Real Devices with Appium: Read Sign-Up Codes in Python (Appium)
- How to Give a Browser Use Agent an Email Address and Let It Read Its Own Verification Code (Browser Use sign-ups)
- How to Receive Email in C#: Read the Inbox, Save Attachments and Get New Mail Pushed (C# / .NET)
- How to Test Email Verification in Cypress: Receive Sign-Up Codes with cy.task (Cypress)
- Ethereal Email Alternative: Test Nodemailer Emails with an Address per Test (Ethereal Email alternative)
- Golang Receive Email: How to Receive and Read Email in Go (Go)
- How to Receive Email in PHP with an Email API: Read the Inbox, Save Attachments and Handle Webhooks (PHP / Laravel)
- How to Receive Email in Python: Read the Inbox, Save Attachments and Get New Mail Pushed (Python)
- Receive Email in Ruby and Rails: Read the Inbox, Save Attachments and Handle Webhooks (Ruby)
- How to Receive Email in Rust: Read the Inbox, Save Attachments and Handle Webhooks in Axum (Rust)
- Add Inbound Email to Your SaaS: Support Intake and Reply-by-Email (SaaS support)
- How to Verify Email in Selenium Tests: Read Sign-Up Codes with Python and pytest (Selenium)
- How to Handle Email Verification in a Stagehand Browser Agent: Create an Address, Wait for the Code, Delete It (Stagehand sign-ups)
- How to Receive Email in Swift: Read the Inbox, Save Attachments and Handle Vapor Webhooks (Swift)
- Test Accounts for Security Testing: a Separate Email Address per Program (Test accounts for security testing)
- How to Automate Email Verification in Tests with Playwright: OTP Codes, Magic Links and Password Resets (Testing email verification)
- How to Receive Email in Node.js: Read the Inbox, Save Attachments and Handle Webhooks (TypeScript / Node.js)
- How to Receive Email with a Webhook: Inbound Email to Your HTTP Endpoint (Webhooks)