Send with

Send email with Java

Java 11 and later include java.net.http.HttpClient. The examples use Jackson for JSON; any JSON library works.

Setup

export ROBUSTEMAIL_API_KEY="rb_test_..."

Add Jackson if your project does not have it yet (com.fasterxml.jackson.core:jackson-databind).

Plain Java

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.Map;

public class RobustEmail {
    private static final URI API = URI.create("https://robustemail.com/api/v2/emails");

    private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
    private final ObjectMapper json = new ObjectMapper();
    private final String apiKey = System.getenv("ROBUSTEMAIL_API_KEY");

    /** Sends one email and returns its ID. */
    public String send(Map<String, Object> email, String idempotencyKey) throws Exception {
        HttpRequest.Builder request = HttpRequest.newBuilder(API)
                .timeout(Duration.ofSeconds(15))
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(json.writeValueAsString(email)));
        if (idempotencyKey != null) {
            request.header("Idempotency-Key", idempotencyKey);
        }

        HttpResponse<String> response = http.send(request.build(), HttpResponse.BodyHandlers.ofString());
        JsonNode body = json.readTree(response.body());
        if (response.statusCode() >= 400) {
            throw new IllegalStateException(body.path("name").asText() + ": " + body.path("message").asText());
        }
        return body.path("id").asText();
    }

    public static void main(String[] args) throws Exception {
        String id = new RobustEmail().send(Map.of(
                "from", "Acme <hello@acme.com>",
                "to", List.of("delivered@sandbox.robustemail.dev"),
                "subject", "Welcome to Acme",
                "html", "<h1>Welcome!</h1><p>Thanks for signing up.</p>"
        ), "welcome-user-1042");
        System.out.println("Queued " + id);
    }
}

Spring Boot

Spring Framework 6.1 and later include RestClient:

@Service
public class EmailService {
    private final RestClient client;

    public EmailService(@Value("${robustemail.api-key}") String apiKey) {
        this.client = RestClient.builder()
                .baseUrl("https://robustemail.com/api/v2")
                .defaultHeader("Authorization", "Bearer " + apiKey)
                .build();
    }

    public String send(Map<String, Object> email, String idempotencyKey) {
        Map<?, ?> body = client.post()
                .uri("/emails")
                .header("Idempotency-Key", idempotencyKey)
                .contentType(MediaType.APPLICATION_JSON)
                .body(email)
                .retrieve() // throws RestClientResponseException on 4xx and 5xx
                .body(Map.class);
        return (String) body.get("id");
    }
}

Set robustemail.api-key from the ROBUSTEMAIL_API_KEY environment variable in application.properties: robustemail.api-key=${ROBUSTEMAIL_API_KEY}.

Attachments

String pdf = Base64.getEncoder().encodeToString(Files.readAllBytes(Path.of("invoice-2041.pdf")));
Map<String, Object> attachment = Map.of(
        "filename", "invoice-2041.pdf",
        "content", pdf,
        "content_type", "application/pdf");
// add "attachments", List.of(attachment) to the email map

Next