メールを送信する
今すぐ、またはあとで 1 通。添付ファイル付きでも、1 回のリクエストで 100 通でも送れます。
メッセージを送信する
Map<String, Object> email = client.emails().send(Body.of( "from", "Acme Billing <[email protected]>", "to", List.of("[email protected]", Body.of("email", "[email protected]", "name", "Grace")), "replyTo", "[email protected]", "subject", "Your September invoice", "html", "<p>Invoice attached.</p>", "text", "Invoice attached."), RequestOptions.create().idempotencyKey("invoice-2026-09-ada")); System.out.println(email.get("id") + " " + email.get("status"));to、cc、bcc にはアドレス 1 つまたはリストを渡せます。アドレスは Ada <[email protected]> のようなテキストか、email と name を持つ map です。本文は html と text、保存済みの template、または draftId から取られます。
すべての送信は冪等性キーを持ちます。クライアントは呼び出しごとにキーを 1 つ作り、再試行でも同じキーを使うため、再試行されたリクエストは最初のメッセージを再生します。プロセスや再起動をまたいでも保証するには、RequestOptions で idempotencyKey を渡してください。
添付ファイル
byte[] report = "month,total".getBytes(StandardCharsets.UTF_8); client.emails().send(Body.of( "from", "[email protected]", "to", "[email protected]", "subject", "Your September report", "text", "The report is attached.", "attachments", List.of( Body.of("filename", "report.csv", "content", report, "contentType", "text/csv"), Body.of("fileId", "b3e1f0a4-6c2d-4e8a-9f17-2d5c8a0b4e6f") )));content には byte[] か Path を渡せ、クライアントが base64 にエンコードします。すでに base64 になっているテキストも渡せます。fileId は client.files().upload でアップロードしたファイルを指し、5 MB を超えるファイルはこの方法で送ります。
あとで送信する
Map<String, Object> scheduled = client.emails().send(Body.of( "from", "[email protected]", "to", "[email protected]", "subject", "Your invoice is due tomorrow", "text", "A reminder that your invoice is due tomorrow.", "scheduledAt", Instant.now().plus(Duration.ofHours(1)))); String id = (String) scheduled.get("id"); client.emails().reschedule(id, Instant.now().plus(Duration.ofHours(2)));client.emails().cancel(id);scheduledAt には Instant、テキストの ISO 8601 の日時、または PT1H のような期間を渡せます。ボディ内のどこにある Instant、OffsetDateTime、ZonedDateTime も、UTC の ISO 8601 の日時として送信されます。予約したメッセージは、送信されるまで変更や取り消しができます。
バッチ送信する
BatchResult batch = client.emails().sendBatch(List.of( Body.of("from", "[email protected]", "to", "[email protected]", "subject", "Your invoice", "text", "Invoice attached."), Body.of("from", "[email protected]", "to", "[email protected]", "subject", "Your invoice", "text", "Invoice attached."))); for (Map<String, Object> item : batch) { if ("error".equals(item.get("status"))) { System.err.println(item.get("index") + " " + item.get("error")); }} System.out.println(batch.sent() + " sent, " + batch.failed() + " failed");バッチには最大 100 件のメッセージを入れられ、全部かゼロかにはなりません。不正なアドレスはその項目だけを失敗させ、残りは送信されます。例外に頼らず、failed() と各項目の status を確認してください。