# Send email with Java

> Send email from Java with the emailit-java SDK or Spring Boot and Jakarta Mail over SMTP, and verify Emailit webhooks in a Spring controller.

This guide shows how to send email from Java with the official `emailit-java` SDK, how to use Spring Boot's mail starter or Jakarta Mail over SMTP instead, and how to verify webhooks in a Spring controller.

## Prerequisites

- Java 11 or later. The Spring examples use Spring Boot 3, which needs Java 17.
- A [verified sending domain](/docs/domains/add-a-domain/), for example `acme.com`.
- An [API key](/docs/developers/api-keys/). A Sending Only key restricted to your domain is enough.
- Until your workspace has [production access](/docs/workspaces/production-access/), you can only send to the account emails of workspace members.

## Install the SDK

Add the dependency, using the latest version from the [emailit-java repository](https://github.com/emailit/emailit-java):

```xml title="pom.xml"
<dependency>
  <groupId>com.emailit</groupId>
  <artifactId>emailit-java</artifactId>
  <version>VERSION</version>
</dependency>
```

```groovy title="build.gradle"
implementation 'com.emailit:emailit-java:VERSION'
```

## Configure your API key

Provide the key as an environment variable:

```bash
```

In Spring Boot, map it to a property so you can inject it:

```properties title="application.properties"
emailit.api-key=${EMAILIT_API_KEY}
```

## Send an email

```java title="SendEmail.java"

public class SendEmail {
    public static void main(String[] args) throws EmailitException {
        EmailitClient emailit = new EmailitClient(System.getenv("EMAILIT_API_KEY"));

        EmailSendParams params = EmailSendParams.builder()
            .setFrom("Acme <hello@acme.com>")
            .setTo(List.of("ada@example.com"))
            .setSubject("Your order has shipped")
            .setHtml("<p>Order #1042 is on its way.</p>")
            .build();

        EmailitObject email = emailit.emails().send(params);
        System.out.println(email.getString("id")); // em_…
    }
}
```

In Spring Boot, register the client once as a bean and inject it where you send:

```java title="EmailitConfig.java"

@Configuration
public class EmailitConfig {
    @Bean
    EmailitClient emailitClient(@Value("${emailit.api-key}") String apiKey) {
        return new EmailitClient(apiKey);
    }
}
```

### Handle errors

The SDK throws typed exceptions that extend `EmailitException`:

```java
try {
    emailit.emails().send(params);
} catch (RateLimitException e) {
    // 429: back off and retry
} catch (AuthenticationException e) {
    // 401: the API key is missing or invalid
} catch (UnprocessableEntityException e) {
    // 422: for example, the from domain isn't verified
} catch (EmailitException e) {
    log.error("Emailit error {}: {}", e.getHttpStatus(), e.getHttpBody());
}
```

## Send with SMTP instead

### Spring Boot

Add `spring-boot-starter-mail` and configure the relay:

```properties title="application.properties"
spring.mail.host=smtp.emailit.com
spring.mail.port=587
spring.mail.username=emailit
spring.mail.password=${EMAILIT_API_KEY}
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
```

Then send with `JavaMailSender`:

```java title="WelcomeMailer.java"

@Service
public class WelcomeMailer {
    private final JavaMailSender mailSender;

    public WelcomeMailer(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void sendWelcome(String to) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("Acme <hello@acme.com>");
        message.setTo(to);
        message.setSubject("Welcome to Acme");
        message.setText("Thanks for signing up.");
        mailSender.send(message);
    }
}
```

Use `MimeMessageHelper` for HTML and attachments.

### Jakarta Mail without Spring

Plain Jakarta Mail (formerly JavaMail) uses the same `mail.smtp.*` properties:

```java
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.emailit.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");

Session session = Session.getInstance(props, new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("emailit", System.getenv("EMAILIT_API_KEY"));
    }
});
```

If port 587 is blocked on your network, use 2525 or 2587 with the same settings. See [SMTP settings](/docs/smtp/settings/).

## Receive webhooks

[Create a webhook](/docs/webhooks/set-up/) and store its signing secret in `EMAILIT_WEBHOOK_SECRET`. Accept the body as a `String` so you verify exactly what Emailit signed:

```java title="EmailitWebhookController.java"

@RestController
public class EmailitWebhookController {
    private final ObjectMapper mapper = new ObjectMapper();
    private final String secret = System.getenv("EMAILIT_WEBHOOK_SECRET");

    @PostMapping("/webhooks/emailit")
    public ResponseEntity<Void> receive(
            @RequestBody String body,
            @RequestHeader(value = "X-Emailit-Signature", defaultValue = "") String signature,
            @RequestHeader(value = "X-Emailit-Timestamp", defaultValue = "0") long timestamp) throws Exception {

        if (Math.abs(System.currentTimeMillis() / 1000 - timestamp) > 300 || !isValid(body, signature, timestamp)) {
            return ResponseEntity.status(401).build();
        }

        // The body is a JSON array of up to 100 events.
        for (JsonNode event : mapper.readTree(body)) {
            if ("email.bounced".equals(event.path("type").asText())) {
                String address = event.path("data").path("object").path("to").asText();
                // Stop emailing this address.
            }
        }
        return ResponseEntity.ok().build();
    }

    private boolean isValid(String body, String signature, long timestamp) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] digest = mac.doFinal((timestamp + "." + body).getBytes(StandardCharsets.UTF_8));
        String expected = HexFormat.of().formatHex(digest);
        return MessageDigest.isEqual(
            expected.getBytes(StandardCharsets.UTF_8),
            signature.getBytes(StandardCharsets.UTF_8));
    }
}
```

If Spring Security is enabled, permit this path and exclude it from CSRF protection. Return a `2xx` within 30 seconds; other responses are retried. See [Request signature](/docs/webhooks/request-signature/).

## Production tips

- **Reuse clients.** Create one `EmailitClient` (or rely on Spring's single `JavaMailSender`) instead of one per message.
- **Send asynchronously.** Use `@Async`, a message queue or a scheduled job for bulk mail, and limit throughput to stay under your [sending limits](/docs/limits/) (2 emails per second by default).
- **Make retries safe.** If you retry after a timeout, send an `Idempotency-Key` header with `java.net.http.HttpClient`; see [Idempotency](/docs/email-api/idempotency/).
- **Deduplicate webhooks** by storing each `event_id` you process.

## Next steps

  - [Send email with the API](/docs/email-api/send-email/): Attachments, scheduling and tracking.
  - [Webhook event types](/docs/webhooks/event-types/): Every event and its payload.
  - [SMTP troubleshooting](/docs/smtp/troubleshooting/): Fix authentication and connection errors.
  - [SDKs and libraries](/docs/sdks/): All official libraries.

---
Source: https://emailit.com/docs/frameworks/java/
