Tutorial
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, for example
acme.com. - An API key. A Sending Only key restricted to your domain is enough.
- Until your workspace has 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:
<dependency>
<groupId>com.emailit</groupId>
<artifactId>emailit-java</artifactId>
<version>VERSION</version>
</dependency>implementation 'com.emailit:emailit-java:VERSION'Configure your API key
Provide the key as an environment variable:
export EMAILIT_API_KEY=secret_••••••••••••••••••••••••••••••••In Spring Boot, map it to a property so you can inject it:
emailit.api-key=${EMAILIT_API_KEY}Send an email
import com.emailit.*;
import com.emailit.exception.*;
import com.emailit.params.*;
import java.util.List;
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:
import com.emailit.EmailitClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@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:
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:
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=trueThen send with JavaMailSender:
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@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:
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.
Receive webhooks
Create a webhook and store its signing secret in EMAILIT_WEBHOOK_SECRET. Accept the body as a String so you verify exactly what Emailit signed:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@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.
Production tips
- Reuse clients. Create one
EmailitClient(or rely on Spring’s singleJavaMailSender) 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 (2 emails per second by default). - Make retries safe. If you retry after a timeout, send an
Idempotency-Keyheader withjava.net.http.HttpClient; see Idempotency. - Deduplicate webhooks by storing each
event_idyou process.