Перейти к документации
C#

Отправка письма

Одно сообщение сейчас или позже, с вложениями, или сотня за один запрос.

Отправка сообщения

send.cs
var sent = await client.Emails.SendAsync(new Body{    ["from"] = "Acme Billing <[email protected]>",    ["to"] = new[] { "[email protected]", "[email protected]" },    ["replyTo"] = "[email protected]",    ["subject"] = "Your September invoice",    ["html"] = "<p>The invoice is attached.</p>",    ["text"] = "The invoice is attached.",    ["tags"] = new Body { ["invoice"] = "inv_2026_09_4192" },}); Console.WriteLine($"{sent["id"]} {sent["status"]}");

to, cc и bcc принимают один адрес или список, а адрес задаётся текстом вроде Ada <[email protected]> или словарём с email и name. Тело берётся из html и text, из сохранённого template или из draftId.

Каждая отправка несёт ключ идемпотентности. Клиент создаёт его для каждого вызова и использует повторно при повторах, поэтому повторённый запрос воспроизводит первое сообщение. Передайте idempotencyKey:, чтобы это сохранялось между процессами и перезапусками.

Вложения

attachments.cs
await using var invoice = File.OpenRead("invoice.pdf"); await client.Emails.SendAsync(new Body{    ["from"] = "[email protected]",    ["to"] = "[email protected]",    ["subject"] = "Your September invoice",    ["text"] = "The invoice is attached.",    ["attachments"] = new[]    {        new Body { ["filename"] = "invoice.pdf", ["content"] = invoice, ["contentType"] = "application/pdf" },        new Body { ["fileId"] = "file_3f9c2a7b1e4d8f60a5c7b92d" },    },});

content принимает byte[] или читаемый Stream, которые клиент кодирует в base64, либо текст, уже закодированный в base64. fileId указывает файл, загруженный через client.Files.UploadAsync(), и именно так отправляется файл больше 5 МБ.

Отправка позже

schedule.cs
var scheduled = await client.Emails.SendAsync(new Body{    ["from"] = "[email protected]",    ["to"] = "[email protected]",    ["subject"] = "Your invoice is due tomorrow",    ["text"] = "A reminder that the invoice is due tomorrow.",    ["scheduledAt"] = DateTimeOffset.UtcNow.AddDays(1),}); var id = scheduled["id"]!.GetValue<string>(); await client.Emails.RescheduleAsync(id, DateTimeOffset.UtcNow.AddDays(2)); var cancelled = await client.Emails.CancelAsync(id); Console.WriteLine(cancelled["status"]);

scheduledAt принимает DateTimeOffset, момент времени в формате ISO 8601 или длительность вроде PT1H. DateTimeOffset в любом месте тела отправляется как момент времени ISO 8601 в UTC. Запланированное сообщение можно изменить или отменить, пока оно не ушло.

Отправка пакета

batch.cs
var result = await client.Emails.SendBatchAsync(new[]{    new Body { ["from"] = "[email protected]", ["to"] = "[email protected]", ["subject"] = "Order AC-4192 has shipped", ["text"] = "It is on its way." },    new Body { ["from"] = "[email protected]", ["to"] = "[email protected]", ["subject"] = "Order AC-4193 has shipped", ["text"] = "It is on its way." },}); Console.WriteLine($"{result.Sent} sent, {result.Failed} failed"); foreach (var item in result){    if ((string?)item["status"] == "error")    {        Console.WriteLine($"{item["index"]} {item["error"]?["message"]}");    }}

Пакет вмещает до 100 сообщений и никогда не работает по принципу всё или ничего: неверный адрес проваливает только свой элемент, а остальные всё равно уходят. Проверяйте Failed и status каждого элемента, а не полагайтесь на исключение.