# Java and .NET

> Use Sendtide from Java and .NET: Spring Mail and MailKit over SMTP, the REST API with HttpClient, verifying webhook signatures and a client generated from the OpenAPI spec.

URL: https://sendtide.ch/en/docs/java-and-net/

There is no dedicated SDK for Java or.NET, and you don't need one: plug Sendtide into Spring Mail or MailKit over SMTP, and use your platform's HTTP client with the REST API for templates, batches and webhooks.
| Option | When | What you get |
| --- | --- | --- |
| SMTP | The application already sends email, for example with Spring Mail, Jakarta Mail or MailKit | Only the configuration changes. Suppressions, limits, logs and webhooks apply as with the API |
| REST API | You want templates, batches, scheduled email or the email’s id right away | Every feature, structured errors, idempotency |
| Generated client | You want typed classes for the whole API | A client generated from the OpenAPI specification, maintained by you |

Create the key in the dashboard under API keys. It belongs in configuration or an environment variable, never in code. With a test key (sk_test_…) you can try everything without anything being delivered.
## SMTP

Server smtp.sendtide.ch, port 587 with STARTTLS, user sendtide, and an API key with at least the send scope as the password. All settings and server replies are under [SMTP](https://sendtide.ch/en/docs/smtp/).
### Spring Boot

With spring-boot-starter-mail, configuration is all it takes:

```
# application.properties
spring.mail.host=smtp.sendtide.ch
spring.mail.port=587
spring.mail.username=sendtide
spring.mail.password=${SENDTIDE_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
```

Send as usual with the JavaMailSender:

```
@Service
public class WelcomeMail {
    private final JavaMailSender mail;

    public WelcomeMail(JavaMailSender mail) {
        this.mail = mail;
    }

    public void send(String to, String name) throws MessagingException {
        MimeMessage message = mail.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8");
        helper.setFrom("Acme <hello@example.ch>");
        helper.setTo(to);
        helper.setSubject("Welcome");
        helper.setText("Hi " + name);
        // optional: a stream of your own
        // message.setHeader("X-Sendtide-Stream", "invoices");
        mail.send(message);
    }
}
```

Without Spring, the same mail.smtp.* settings apply to Jakarta Mail directly.
###.NET with MailKit

```
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;

var message = new MimeMessage();
message.From.Add(new MailboxAddress("Acme", "hello@example.ch"));
message.To.Add(MailboxAddress.Parse("anna@example.com"));
message.Subject = "Welcome";
message.Body = new TextPart("plain") { Text = "Hi Anna" };
// optional: message.Headers.Add("X-Sendtide-Stream", "invoices");

using var smtp = new SmtpClient();
await smtp.ConnectAsync("smtp.sendtide.ch", 587, SecureSocketOptions.StartTls);
await smtp.AuthenticateAsync("sendtide", Environment.GetEnvironmentVariable("SENDTIDE_API_KEY"));
await smtp.SendAsync(message);
await smtp.DisconnectAsync(true);
```

In ASP.NET Core, put the key in configuration (Sendtide:ApiKey in appsettings.json or the environment variable Sendtide__ApiKey) and read it through IConfiguration. For many emails in a row, keep the connection open and send several messages instead of reconnecting for each one. Microsoft no longer recommends the old System.Net.Mail.SmtpClient; use MailKit.
### Good to know
- MimeKit and Jakarta Mail set a Message-ID. Sendtide uses it to recognise retries: if you send the same message again after a dropped connection, it does not go out twice. So for a retry, send the same message object instead of building a new one.
- Replies 451 and 452 are temporary, 550 and 552 are final. Spring reports them as MailSendException, MailKit as SmtpCommandException with a StatusCode.
- SMTP has no templates and returns no id. If you need those, use the REST API.
## REST API

A POST to https://api.sendtide.ch/v1/emails with the key in the Authorization header. The reply is 202 with the email’s id. Set an Idempotency-Key so you can safely retry after a network error. All fields are under [Sending email](https://sendtide.ch/en/docs/sending-email/).

```
// Java 17, standard library only
HttpClient http = HttpClient.newHttpClient();

String json = """
    {"from": "Acme <hello@example.ch>", "to": "anna@example.com",
     "template": "welcome", "locale": "en", "data": {"name": "Anna"}}
    """;

HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.sendtide.ch/v1/emails"))
    .header("Authorization", "Bearer " + System.getenv("SENDTIDE_API_KEY"))
    .header("Content-Type", "application/json")
    .header("Idempotency-Key", "welcome-" + userId)
    .POST(HttpRequest.BodyPublishers.ofString(json))
    .build();

HttpResponse<String> response = http.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 202) {
    // {"error": {"code": "...", "message": "...", "field": "..."}}
    throw new IllegalStateException(response.body());
}
```

```
// .NET 8, Program.cs: a named HttpClient for Sendtide
builder.Services.AddHttpClient("sendtide", c =>
{
    c.BaseAddress = new Uri("https://api.sendtide.ch/");
    c.DefaultRequestHeaders.Authorization = new("Bearer", builder.Configuration["Sendtide:ApiKey"]);
});

// when sending, with IHttpClientFactory factory
var http = factory.CreateClient("sendtide");
using var request = new HttpRequestMessage(HttpMethod.Post, "v1/emails")
{
    Content = JsonContent.Create(new
    {
        @from = "Acme <hello@example.ch>",
        to = "anna@example.com",
        template = "welcome",
        locale = "en",
        data = new { name = "Anna" },
    }),
};
request.Headers.Add("Idempotency-Key", $"welcome-{userId}");

var response = await http.SendAsync(request);
if (response.StatusCode != HttpStatusCode.Accepted)
{
    // {"error": {"code": "...", "message": "...", "field": "..."}}
    throw new InvalidOperationException(await response.Content.ReadAsStringAsync());
}
```

Retry network errors, 429 (after Retry-After) and 5xx, nothing else. Only retry a POST that carries an idempotency key. In.NET, Microsoft.Extensions.Http.Resilience handles this, in Java Resilience4j or Spring Retry. Which error gets which reply is under [Errors and limits](https://sendtide.ch/en/docs/errors-and-limits/).
### Verify webhooks

Every webhook request carries the header Sendtide-Signature: t=…,v1=…. Check the HMAC-SHA256 over "<t>.<raw body>" with the webhook’s secret, and reject requests older than 5 minutes. More under [Webhooks](https://sendtide.ch/en/docs/webhooks/#verify-the-signature).

```
// Spring Boot
@PostMapping("/webhooks/sendtide")
public ResponseEntity<Void> webhook(@RequestHeader(value = "Sendtide-Signature", defaultValue = "") String header,
                                    @RequestBody byte[] body) throws Exception {
    Map<String, String> parts = new HashMap<>();
    for (String p : header.split(",")) {
        String[] kv = p.trim().split("=", 2);
        if (kv.length == 2) parts.put(kv[0], kv[1]);
    }
    String t = parts.getOrDefault("t", "");
    if (!t.matches("\\d{1,12}") || Math.abs(Instant.now().getEpochSecond() - Long.parseLong(t)) > 300) {
        return ResponseEntity.badRequest().build();
    }
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(System.getenv("SENDTIDE_WEBHOOK_SECRET").getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
    mac.update((t + ".").getBytes(StandardCharsets.UTF_8));
    byte[] expected = HexFormat.of().formatHex(mac.doFinal(body)).getBytes(StandardCharsets.UTF_8);
    byte[] given = parts.getOrDefault("v1", "").getBytes(StandardCharsets.UTF_8);
    if (!MessageDigest.isEqual(expected, given)) {
        return ResponseEntity.badRequest().build();
    }
    // read body as JSON, for example with Jackson
    return ResponseEntity.ok().build();
}
```

```
// ASP.NET Core, minimal API
app.MapPost("/webhooks/sendtide", async (HttpRequest req, IConfiguration config) =>
{
    using var buffer = new MemoryStream();
    await req.Body.CopyToAsync(buffer);
    var body = buffer.ToArray(); // raw body

    var parts = new Dictionary<string, string>();
    foreach (var p in req.Headers["Sendtide-Signature"].ToString().Split(','))
    {
        var kv = p.Trim().Split('=', 2);
        if (kv.Length == 2) parts[kv[0]] = kv[1];
    }
    var t = parts.GetValueOrDefault("t", "");
    if (!long.TryParse(t, out var ts) || Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - ts) > 300)
        return Results.BadRequest();

    var secret = Encoding.UTF8.GetBytes(config["Sendtide:WebhookSecret"]!);
    var signed = Encoding.UTF8.GetBytes(t + ".").Concat(body).ToArray();
    var expected = Encoding.UTF8.GetBytes(Convert.ToHexString(HMACSHA256.HashData(secret, signed)).ToLowerInvariant());
    var given = Encoding.UTF8.GetBytes(parts.GetValueOrDefault("v1", ""));
    if (!CryptographicOperations.FixedTimeEquals(expected, given))
        return Results.BadRequest();

    using var evt = JsonDocument.Parse(body);
    // evt.RootElement.GetProperty("type").GetString() ...
    return Results.Ok();
});
```

Sendtide delivers webhooks at least once. Recognise repeats by the event id (evt_…) and answer 2xx for them as well.
## Generated client

The whole API is described as [OpenAPI 3.1](https://api.sendtide.ch/v1/openapi.json). Generate a typed client from it, for example with the [OpenAPI Generator](https://openapi-generator.tech/) (-g java or -g csharp) or Microsoft’s [Kiota](https://learn.microsoft.com/openapi/kiota/) for.NET and Java:

```
npx @openapitools/openapi-generator-cli generate \
  -i https://api.sendtide.ch/v1/openapi.json -g csharp -o Sendtide.Client
```

Check your generator version’s support for OpenAPI 3.1. You maintain the generated code yourself: regenerate it when Sendtide extends the API, and pin the [API version](https://sendtide.ch/en/docs/api-versions/) you generated it against.

Missing an official SDK for Java or.NET? Tell us what you need.
