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

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

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

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

send.go
sent, err := client.Emails.Send(ctx, openemail.Body{	"from":    "Acme Billing <[email protected]>",	"to":      []string{"[email protected]", "[email protected]"},	"replyTo": "[email protected]",	"subject": "Your September invoice",	"html":    "<p>The invoice is attached.</p>",	"text":    "The invoice is attached.",	"tags":    openemail.Body{"invoice": "inv_2026_09_4192"},})if err != nil {	return err} fmt.Println(sent.ID(), sent.String("status"))

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

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

Вложения

attachments.go
invoice, err := os.ReadFile("invoice.pdf")if err != nil {	return err} _, err = client.Emails.Send(ctx, openemail.Body{	"from":    "[email protected]",	"to":      "[email protected]",	"subject": "Your September invoice",	"text":    "The invoice is attached.",	"attachments": []openemail.Body{		{"filename": "invoice.pdf", "content": invoice, "contentType": "application/pdf"},		{"fileId": "file_3f9c2a7b1e4d8f60a5c7b92d"},	},}) return err

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

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

schedule.go
scheduled, err := client.Emails.Send(ctx, openemail.Body{	"from":        "[email protected]",	"to":          "[email protected]",	"subject":     "Your invoice is due tomorrow",	"text":        "A reminder that the invoice is due tomorrow.",	"scheduledAt": time.Now().Add(24 * time.Hour),})if err != nil {	return err} if _, err := client.Emails.Reschedule(ctx, scheduled.ID(), time.Now().Add(48*time.Hour)); err != nil {	return err} cancelled, err := client.Emails.Cancel(ctx, scheduled.ID())if err != nil {	return err} fmt.Println(cancelled.String("status"))

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

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

batch.go
result, err := client.Emails.SendBatch(ctx, []openemail.Body{	{"from": "[email protected]", "to": "[email protected]", "subject": "Order AC-4192 has shipped", "text": "It is on its way."},	{"from": "[email protected]", "to": "[email protected]", "subject": "Order AC-4193 has shipped", "text": "It is on its way."},})if err != nil {	return err} fmt.Println(result.Sent, "sent,", result.Failed, "failed") for _, item := range result.Items {	if item.String("status") == "error" {		fmt.Println(item.Int("index"), item.Object("error").String("message"))	}}

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