安装
go get github.com/deveryidea/voaaro-go@latest版本 0.4.0。需要 Go 1.21 或更高版本,无任何依赖(标准库)。包名为 voaaro。
配置
import "github.com/deveryidea/voaaro-go"
client := voaaro.NewClient(os.Getenv("VOAARO_API_KEY"),
voaaro.WithBaseURL("https://mail.example.com"),
voaaro.WithMaxRetries(2)) // default; 0: no retry and no idempotency key drawn选项:WithBaseURL、WithMaxRetries、WithHTTPClient、WithUserAgent、WithHeader。默认超时:60 秒。请始终通过 WithBaseURL(或 VOAARO_BASE_URL)提供您的实例地址。
发送
pdf, _ := os.ReadFile("guide.pdf")
sent, err := client.Emails.SendWithOptions(ctx, &voaaro.SendEmailRequest{
From: "Acme <notifications@example.com>",
To: []string{"client@example.org"},
Subject: "Welcome",
Html: "<p>Your account is ready.</p>",
Attachments: []*voaaro.Attachment{{Filename: "guide.pdf", Content: pdf}}, // raw bytes
}, &voaaro.SendEmailOptions{IdempotencyKey: "welcome-42"})
if err != nil {
var apiErr *voaaro.Error
if errors.As(err, &apiErr) {
log.Println(apiErr.StatusCode, apiErr.Name, apiErr.Message, apiErr.RetryAfter)
}
return err
}
log.Println(sent.Id)每个方法都有对应的 …WithContext(ctx, …) 版本。
重试与幂等性
- 遇到网络错误、
429 rate_limit_exceeded或 500、502、503、504 时,SDK 会自动重试请求:默认重试 2 次(WithMaxRetries(n))。遇到daily_quota_exceeded或其他4xx错误时从不重试。等待时间:以Retry-After为准(最多 60 秒),否则为 0.5 秒 × 2^n 并加入随机抖动,最多 8 秒;取消context会终止等待。 - 每个创建请求都有一个
IdempotencyKey字段(CreateContactRequest、CreateWebhookRequest、AddSuppressionRequest、CreateFormRequest等);对于其他任何POST,请将voaaro.WithIdempotencyKey(ctx, key)与WithContext版本配合使用。 - 未提供键时,只要允许重试,SDK 就会为每个
POST生成一个 UUID v4,并在各次尝试之间保持不变。
ctx := voaaro.WithIdempotencyKey(context.Background(), "cancel-broadcast-42")
client.Broadcasts.CancelWithContext(ctx, broadcastId)分页
每个基于游标的列表都有一个 Iter[T] 迭代器(不使用对函数的 range 遍历,以兼容 Go 1.21):
it := client.Contacts.ListAll(ctx, &voaaro.ListContactsOptions{SegmentId: segmentId})
for it.Next() {
c := it.Current()
fmt.Println(c.Id, c.Email)
}
if err := it.Err(); err != nil {
log.Fatal(err)
}
all, err := client.Webhooks.ListAll(ctx, nil).All() // everything at once, for a short list- 每页 100 条(或
Limit),只要has_more为真就沿着after继续;只在需要时才请求下一页。选项中的筛选条件在每一页都会保留;Before会被忽略。 - 出错时遍历会停止:
Next返回false,Err返回该错误。 ListAll可用于Emails、Emails.Receiving、ApiKeys、Domains、Suppressions、Contacts、Contacts.Imports、Segments、Broadcasts、Forms、NewsletterTemplates、Automations、Webhooks、Webhooks.Deliveries;此外还有Emails.EventsAll、Segments.ListContactsAll、Broadcasts.RecipientsAll、Forms.SignupsAll、Automations.RunsAll。
其他功能
client.Batch.SendWithOptions(ctx, reqs, &voaaro.BatchSendEmailOptions{BatchValidation: voaaro.BatchValidationPermissive})
client.Emails.Get(id)
client.Emails.List()
client.Emails.Update(&voaaro.UpdateEmailRequest{Id: id, ScheduledAt: "in 2 hours"})
client.Emails.Cancel(id)
client.Emails.Events(&voaaro.ListEmailEventsOptions{Type: "bounced", CreatedAfter: "2026-11-01T00:00:00Z"})
client.Emails.Receiving.List(&voaaro.ListReceivedOptions{ListOptions: voaaro.ListOptions{Limit: 10}})
client.Domains.Create(&voaaro.CreateDomainRequest{Name: "notify.example.com"})
client.Suppressions.Add(&voaaro.AddSuppressionRequest{Email: "former.customer@example.org", Domain: "example.com"})
client.ApiKeys.Create(&voaaro.CreateApiKeyRequest{Name: "CI", Permission: voaaro.PermissionSendingAccess})
client.Contacts.Create(&voaaro.CreateContactRequest{Email: "ada@example.org", FirstName: "Ada"})
client.Broadcasts.Create(&voaaro.CreateBroadcastRequest{SegmentId: segmentId, From: from, Subject: subject, Html: html, Send: true})服务:Emails(含 Attachments 和 Receiving)、Batch、ApiKeys、Domains、Suppressions、Contacts(含 Imports)、Segments、Audiences、Topics、ContactProperties、Broadcasts、Newsletter、Forms、NewsletterTemplates、Automations、Events、Webhooks(含 Deliveries)、Organizations(运营方密钥 mko_…)。
新闻通讯
client.Newsletter.UpdateSettings(&voaaro.UpdateNewsletterSettingsRequest{
From: voaaro.String("Acme <news@example.com>"),
PostalAddress: voaaro.String("Acme\n12 Lilac Street\nSpringfield"),
})
o, _ := client.Newsletter.Overview(&voaaro.NewsletterOverviewOptions{Days: 30})
f, _ := client.Forms.Create(&voaaro.CreateFormRequest{Name: "Website newsletter", SegmentIds: []string{segmentId}})
filter := &voaaro.SegmentFilter{Match: "all", Conditions: []voaaro.SegmentCondition{{"field": "opened", "op": "none", "days": 90}}}
preview, _ := client.Segments.Preview(&voaaro.PreviewSegmentRequest{Filter: filter})
client.Broadcasts.Links(broadcastId)
client.Broadcasts.ChooseWinner(broadcastId, "b")
csv, _ := client.Broadcasts.Export(broadcastId) // []byte
tpl, _ := client.NewsletterTemplates.Create(&voaaro.CreateNewsletterTemplateRequest{Name: "Monthly letter", Subject: "What's new", Html: html})
client.Events.Send(&voaaro.SendEventRequest{Email: "ada@example.org", Name: "purchase", Data: map[string]any{"total": 42}})
client.Contacts.Cleanup(&voaaro.CleanupContactsRequest{Days: 180}) // simulation; DryRun: voaaro.Bool(false) to actAutomations.Create 接受一个 AutomationTrigger 和若干 AutomationStep;当密钥覆盖多个域名时,用 Domain 字段指定域名。路由详情:新闻通讯。
从您的应用进行订阅和退订(服务器端:Newsletter.Subscribe、Unsubscribe、GetSubscription;浏览器端:NewPublicForm、SolveChallenge),以及营销邮件定时发送(Broadcasts.Schedule、Unschedule、SendNow、ListScheduled、Check):请参见指南您自己的订阅表单、从您的应用退订和定时发送营销邮件,其中提供了每种 SDK 的示例。
联系人质量与送达率:验证地址但不保存(Contacts.VerifyEmail)或重新验证联系人的地址(Contacts.Reverify),按参与度和地址状态筛选(Engagement、EmailStatus),导出 CSV(Contacts.Export),导入时排除无效地址(SkipInvalid),以及营销邮件的送达率评分(Broadcasts.Deliverability):请参见联系人、分组和主题和营销邮件,其中提供了每种 SDK 的示例。
Webhook
event, err := voaaro.VerifyWebhookRequest(r, os.Getenv("VOAARO_WEBHOOK_SECRET"))读取请求体(最多 5 MB)后将其放回原处,并验证签名和时效(5 分钟);出错时,errors.Is(err, voaaro.ErrWebhookVerification) 为真。
多个签名密钥:使用 voaaro.VerifyWebhookRequestWithSecrets(r, newSecret, oldSecret)、voaaro.VerifyWebhookWithSecrets(body, signature, newSecret, oldSecret),或在 client.Webhooks.Verify 中使用 VerifyWebhookOptions 的 WebhookSecrets 字段。只要其中一个签名密钥与请求头中的某个 v1 匹配,通知即被接受。完整示例和轮换:签名。
管理端点(详情):
hook, _ := client.Webhooks.Create(&voaaro.CreateWebhookRequest{
Endpoint: "https://app.example.com/webhooks/voaaro",
Events: []string{"email.bounced"},
})
secret := hook.SigningSecret // shown only once
client.Webhooks.RotateSecret(hook.Id, &voaaro.RotateWebhookSecretRequest{GraceHours: voaaro.Int(24)})
it := client.Webhooks.Deliveries.ListAll(ctx, hook.Id, &voaaro.ListWebhookDeliveriesOptions{Status: "failed"})
for it.Next() {
client.Webhooks.Deliveries.Replay(hook.Id, it.Current().Id)
}