GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitHub - mailtrap/mailtrap-java: Official mailtrap.io Java client

BranchesTags
Open more actions menu

Latest commit

 

History

300 Commits
300 Commits

Folders and files

NameName
Last commit message
Last commit date
.github
.github
 
 
.idea
.idea
 
 
docs
docs
 
 
examples
examples
 
 
src
src
 
 
.envrc
.envrc
 
 
.gitignore
.gitignore
 
 
.tool-versions
.tool-versions
 
 
CHANGELOG.md
CHANGELOG.md
 
 
CODE_OF_CONDUCT.md
CODE_OF_CONDUCT.md
 
 
LICENSE.txt
LICENSE.txt
 
 
README.md
README.md
 
 
pom.xml
pom.xml
 
 

Repository files navigation

Mailtrap Java client - Official

JDK 11+ Maven Central

Prerequisites

To get the most of this official Mailtrap.io Java SDK:

  • Create a Mailtrap account
  • Verify your domain

Install package

As a Maven dependency:

<dependency>
    <groupId>io.mailtrap</groupId>
    <artifactId>mailtrap-java</artifactId>
    <version>1.11.0</version>
</dependency>

As a Gradle Groovy dependency:

implementation 'io.mailtrap:mailtrap-java:1.11.0'

As a Gradle Kotlin DSL dependency:

implementation("io.mailtrap:mailtrap-java:1.11.0")

Usage

Minimal usage (Transactional sending)

The quickest way to send a single transactional email with only the required parameters:

import io.mailtrap.client.MailtrapClient;
import io.mailtrap.config.MailtrapConfig;
import io.mailtrap.factory.MailtrapClientFactory;
import io.mailtrap.model.request.emails.Address;
import io.mailtrap.model.request.emails.MailtrapMail;

import java.util.List;

public class MailtrapJavaSDKTest {

    private static final String TOKEN = "<YOUR MAILTRAP TOKEN>";
    private static final String SENDER_EMAIL = "[email protected]";
    private static final String RECIPIENT_EMAIL = "[email protected]";

    public static void main(String[] args) {
        final MailtrapConfig config = new MailtrapConfig.Builder()
            .token(TOKEN)
            .build();

        final MailtrapClient client = MailtrapClientFactory.createMailtrapClient(config);

        final MailtrapMail mail = MailtrapMail.builder()
            .from(new Address(SENDER_EMAIL))
            .to(List.of(new Address(RECIPIENT_EMAIL)))
            .subject("Hello from Mailtrap Sending!")
            .text("Welcome to Mailtrap Sending!")
            .build();

        // Send an email using Mailtrap Sending API
        try {
            System.out.println(client.send(mail));
        } catch (Exception e) {
            System.out.println("Caught exception : " + e);
        }
    }
}

Sandbox vs Production (easy switching)

Mailtrap lets you test safely in the Email Sandbox and then switch to Production (Sending) with one flag.

Example config init:

        final MailtrapConfig config = new MailtrapConfig.Builder()
    .token("<YOUR MAILTRAP TOKEN>")
    .sandbox(true)
    .sandboxId(123456)
    .build();

Bootstrap logic:

import io.mailtrap.client.MailtrapClient;
import io.mailtrap.config.MailtrapConfig;
import io.mailtrap.factory.MailtrapClientFactory;
import io.mailtrap.model.request.emails.Address;
import io.mailtrap.model.request.emails.MailtrapMail;

import java.util.List;

public class MailtrapJavaSDKSandboxTest {

    private static final String TOKEN = "<YOUR MAILTRAP TOKEN>";
    private static final String SENDER_EMAIL = "[email protected]";
    private static final String RECIPIENT_EMAIL = "[email protected]";
    private static final long SANDBOX_ID = 1L;

    public static void main(String[] args) {
        final MailtrapConfig config = new MailtrapConfig.Builder()
            .token(TOKEN)
            .sandbox(true)
            .sandboxId(SANDBOX_ID)
            .build();

        final MailtrapClient client = MailtrapClientFactory.createMailtrapClient(config);

        final MailtrapMail mail = MailtrapMail.builder()
            .from(new Address(SENDER_EMAIL))
            .to(List.of(new Address(RECIPIENT_EMAIL)))
            .subject("Hello from Mailtrap Sandbox Sending!")
            .text("Welcome to Mailtrap Sandbox Sending!")
            .build();

        // Send an email using Mailtrap Sending API
        try {
            System.out.println(client.send(mail));
        } catch (Exception e) {
            System.out.println("Caught exception : " + e);
        }
    }
}

Bulk stream example (optional) differs only by setting .bulk(true) instead of .sandbox(true):

        final MailtrapConfig config = new MailtrapConfig.Builder()
    .token(TOKEN)
    .bulk(true)
    .build();

Alternatively, you can switch between Sandbox, Production and Bulk sending from client directly

import io.mailtrap.client.MailtrapClient;
import io.mailtrap.config.MailtrapConfig;
import io.mailtrap.factory.MailtrapClientFactory;
import io.mailtrap.model.request.emails.Address;
import io.mailtrap.model.request.emails.MailtrapMail;

import java.util.List;

public class SwitchSendFromClient {

    private static final String TOKEN = "<YOUR MAILTRAP TOKEN>";
    private static final String SENDER_EMAIL = "[email protected]";
    private static final String RECIPIENT_EMAIL = "[email protected]";
    private static final long SANDBOX_ID = 1L;

    public static void main(String[] args) {
        // Minimal config init, just token
        final MailtrapConfig config = new MailtrapConfig.Builder()
            .token(TOKEN)
            .build();

        final MailtrapClient client = MailtrapClientFactory.createMailtrapClient(config);

        final MailtrapMail mail = MailtrapMail.builder()
            .from(new Address(SENDER_EMAIL))
            .to(List.of(new Address(RECIPIENT_EMAIL)))
            .subject("Hello from Mailtrap Sending!")
            .text("Welcome to Mailtrap Sending!")
            .build();
        
        // Production send
        client.send(mail);
        
        // Bulk send
        client.switchToBulkSendingApi();
        client.send(mail);
        
        // Sandbox send
        client.switchToEmailSandboxApi(SANDBOX_ID);
        client.send(mail);
    }

}

Full-featured usage example

import io.mailtrap.config.MailtrapConfig;
import io.mailtrap.factory.MailtrapClientFactory;
import io.mailtrap.model.request.emails.Address;
import io.mailtrap.model.request.emails.EmailAttachment;
import io.mailtrap.model.request.emails.MailtrapMail;
import io.mailtrap.model.response.emails.SendResponse;

import java.io.InputStream;
import java.util.Base64;
import java.util.List;
import java.util.Map;

public class FullFeaturedExample {

    private static final String TOKEN = "<YOUR MAILTRAP TOKEN>";
    private static final String SENDER_EMAIL = "[email protected]";
    private static final String RECIPIENT_EMAIL = "[email protected]";
    private static final String REPLY_TO_EMAIL = "[email protected]";

    public static void main(String[] args) {
        final var config = new MailtrapConfig.Builder()
                .token(TOKEN)
            //by default both `bulk` and `sandbox` are null, `sandboxId` is null
                .build();

        final var client = MailtrapClientFactory.createMailtrapClient(config);

        final String welcomeImage = readAndEncodeAttachment("welcome.png");

        final var mail = MailtrapMail.builder()
                .category("Test message")
                .customVariables(Map.of(
                        "hello", "world",
                        "year", "2024",
                        "anticipated", "true"
                ))
                .from(new Address(SENDER_EMAIL))
                .to(List.of(new Address(RECIPIENT_EMAIL)))
                .replyTo(new Address(REPLY_TO_EMAIL, "Reply To"))
                .subject("Hello from Mailtrap!")
                .html("""
                        <!doctype html>
                        <html>
                          <head>
                            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                          </head>
                          <body style="font-family: sans-serif;">
                            <div style="display: block; margin: auto; max-width: 600px;" class="main">
                              <h1 style="font-size: 18px; font-weight: bold; margin-top: 20px">Congrats for sending test email with Mailtrap!</h1>
                              <p>Inspect it using the tabs you see above and learn how this email can be improved.</p>
                              <img alt="Inspect with Tabs" src="cid:welcome.png" style="width: 100%;">
                              <p>Now send your email using our fake SMTP server and integration of your choice!</p>
                              <p>Good luck! Hope it works.</p>
                            </div>
                            <!-- Example of invalid for email html/css, will be detected by Mailtrap: -->
                            <style>
                              .main { background-color: white; }
                              a:hover { border-left-width: 1em; min-height: 2em; }
                            </style>
                          </body>
                        </html>
                        """)
                .attachments(List.of(EmailAttachment.builder()
                        .filename("welcome.png")
                        .contentId("welcome.png")
                        .disposition("inline")
                        .content(welcomeImage)
                        .build()))
                .build();

        // Custom email headers (optional)
        final Map<String, String> headers = mail.getHeaders();
        headers.put("X-Message-Source", "domain.com");
        headers.put("X-Mailer", "Mailtrap Java Client");


        try {
            final SendResponse response = client.sendingApi().emails().send(mail);
            System.out.println(response);
        }catch (final Exception e) {
            System.err.println("Failed to send mail: " + e.getMessage());
        }


        // OR Template email sending

        
        final var templateMail = MailtrapMail.builder()
            .from(new Address("John Doe", SENDER_EMAIL))
            .to(List.of(new Address("Jane Doe", RECIPIENT_EMAIL)))
            .templateUuid("813e39db-0000-0000-0000-0e6ba8b1fe88")
            .templateVariables(Map.of(
                "user_name", "Jack Sparrow",
                "next_step_link", "https://mailtrap.io/",
                "get_started_link", "https://mailtrap.io/",
                "integer", 123,
                "boolean", false
            ))
            .build();

        try {
            final SendResponse response = client.sendingApi().emails().send(templateMail);
            System.out.println(response);
        }catch (final Exception e) {
            System.err.println("Failed to send mail: " + e.getMessage());
        }

    }

    private static String readAndEncodeAttachment(final String filename) {
        try (final InputStream inputStream = FullFeaturedExample.class.getClassLoader().getResourceAsStream(filename)) {
            if (inputStream == null) {
                return "";
            }
            return Base64.getEncoder().encodeToString(inputStream.readAllBytes());
        } catch (final Exception e) {
            return "";
        }
    }
}

Refer to the examples folder for the source code of this and other advanced examples.

API Reference and supported functionality

You can find the Mailtrap Java API reference documentation.

General API

  • Account Accesses
  • Accounts
  • Permissions
  • Billing
  • API Tokens
  • Webhooks
  • Verifying webhook signatures

Organizations API

  • Sub-Accounts

Sending API

  • Advanced
  • Minimal
  • Error handling
  • Send using template
  • Batch
  • Domains
  • Company Info
  • Suppressions
  • Tracking Opt-outs
  • Stats
  • Email Logs

Email Sandbox API

  • Attachments
  • Sandboxes
  • Messages
  • Projects
  • Sandbox send using template
  • Batch

Inbound Email API

  • Folders
  • Inboxes
  • Messages
  • Threads
  • Forward Rules

Bulk Sending API

  • Bulk send
  • Batch

Contacts API

  • Contacts
  • Contact Lists
  • Contact Exports
  • Contact Fields
  • Contact Imports

Email Templates API

  • Templates (experimental)
  • Email Templates

Email Marketing API

  • Email Campaigns
  • Marketing Stats

Renamed APIs

The SDK now uses the product's names: Email Testing inboxes are sandboxes and sending domains are domains. The old entry points still work and call the same endpoints, but they are marked @Deprecated(since = "1.11.0") and will be removed in a future major release. Types such as MailtrapEmailTestingApi, Inboxes, InboxResponse, SendingDomains and SendingDomainsResponse keep their names until that release.

Old New
client.testingApi() client.sandboxApi()
client.switchToEmailTestingApi(inboxId) client.switchToEmailSandboxApi(sandboxId)
new MailtrapConfig.Builder().inboxId(id) new MailtrapConfig.Builder().sandboxId(id)
config.getInboxId() config.getSandboxId()
Constants.EMAIL_TESTING_SEND_HOST Constants.EMAIL_SANDBOX_SEND_HOST
sandboxApi().inboxes() sandboxApi().sandboxes()
createInbox(accountId, projectId, request) createSandbox(accountId, projectId, request)
getInboxAttributes(accountId, inboxId) getSandboxAttributes(accountId, sandboxId)
updateInbox(accountId, inboxId, request) updateSandbox(accountId, sandboxId, request)
deleteInbox(accountId, inboxId) deleteSandbox(accountId, sandboxId)
cleanInbox(accountId, inboxId) cleanSandbox(accountId, sandboxId)
getInboxes(accountId) getSandboxes(accountId)
sendingApi().domains().getSendingDomains(accountId) sendingApi().domains().getDomains(accountId)
getSendingDomain(accountId, sendingDomainId) getDomain(accountId, domainId)
sendSendingDomainsSetupInstructions(accountId, sendingDomainId, request) sendDomainSetupInstructions(accountId, domainId, request)
deleteSendingDomain(accountId, sendingDomainId) deleteDomain(accountId, domainId)

Contributing

Bug reports and pull requests are welcome on GitHub. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.

Build

  • Install direnv
  • Install asdf
  • Install asdf-java plugin
  • Install asdf-maven plugin

License

The package is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the Mailtrap project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.

About

Official mailtrap.io Java client

mailtrap.io

Resources

Readme
MIT license

Code of conduct

Code of conduct
Activity
Custom properties

Stars

10 stars

Watchers

9 watching

Forks

1 fork
Report repository

Releases

Packages

Used by

Contributors

Languages

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.