Install the Resend Go SDK
mainTo install the Resend Go SDK in your Go project, run the following command in your terminal:
go get github.com/resend/resend-go/v4repository·main·Indexed 42 days ago
https://github.com/resend/resend-goA programmatic interface for interacting with the Resend email platform using Go. The SDK (v4) allows developers to send individual and batch emails, manage API keys, handle broadcasts, and configure automations. It includes support for batch validation modes (Strict and Permissive) and provides a migration path from the deprecated Audiences API to the Segments API.
To install the Resend Go SDK in your Go project, run the following command in your terminal:
go get github.com/resend/resend-go/v4When creating or updating a template, any variable used in the HTML content (e.g., {{{NAME}}}) must be explicitly declared in the Variables array. Failure to declare a variable used in the HTML will result in an API validation error.
TemplateVariable fields:
Key: The name of the variable (e.g., NAME).Type: The VariableType (VariableTypeString or VariableTypeNumber).FallbackValue: An optional value to use if the variable is not provided during email sending.params := &resend.CreateTemplateRequest{
Name: "My Template",
Html: "<div>Hello {{{USER_NAME}}}!</div>",
Variables: []*resend.TemplateVariable{
{
Key: "USER_NAME",
Type: resend.VariableTypeString,
FallbackValue: "Guest",
},
},
}Suppressions in Resend are categorized by their SuppressionOrigin. This helps identify why an email address was added to the list.
SuppressionOriginBounce ("bounce"): The email bounced.SuppressionOriginComplaint ("complaint"): The recipient marked the email as spam.SuppressionOriginManual ("manual"): The suppression was added manually via the API.SuppressionListEntry: Used in List responses. It does not contain an Object field.Suppression: Used in Get responses. Includes the Object field.SourceId: A pointer to a string that identifies the specific event (like a bounce event ID) that caused the suppression. This is nil for manual suppressions.Automations are composed of AutomationStep objects and AutomationConnection objects that define the workflow logic.
Each step has a Key, a Type, and a Config map for step-specific parameters.
Supported AutomationStepType values:
triggersend_emaildelaywait_for_eventconditioncontact_updatecontact_deleteadd_to_segmentConnections define how the flow moves from one step to another using From and To keys.
Supported AutomationConnectionType values:
defaultcondition_metcondition_not_mettimeoutevent_receivedsteps := []resend.AutomationStep{
{Key: "start", Type: resend.AutomationStepTypeTrigger, Config: map[string]any{}},
{Key: "email", Type: resend.AutomationStepTypeSendEmail, Config: map[string]any{"template_id": "abc"}},
}
connections := []resend.AutomationConnection{
{From: "start", To: "email", Type: resend.AutomationConnectionTypeDefault},
}When sending batches of emails, you can control how the API handles invalid email requests using BatchValidationMode.
BatchValidationStrict: The default mode. The entire batch is only sent if all emails in the request are valid. If any email is invalid, the whole batch fails.BatchValidationPermissive: Allows partial success. The API will process all valid emails in the batch and return a list of specific errors for the invalid ones.// Use BatchValidationPermissive to allow some emails to succeed even if others fail
options := &resend.BatchSendEmailOptions{
BatchValidation: resend.BatchValidationPermissive,
}Options implementation that provides an idempotency key. The SDK will automatically set the Idempotency-Key header for POST requests if a key is provided.The Audiences API is deprecated and has been renamed to Segments. While the AudiencesSvc and its associated types are maintained for backward compatibility, they internally call the Segments API. For all new development, you should use the SegmentsSvc and its corresponding types to ensure long-term compatibility and access to the latest features.
Mapping of deprecated types to new types:
AudiencesSvc $\rightarrow$ SegmentsSvcAudiencesSvcImpl $\rightarrow$ SegmentsSvcImplCreateAudienceRequest $\rightarrow$ CreateSegmentRequestCreateAudienceResponse $\rightarrow$ CreateSegmentResponseRemoveAudienceResponse $\rightarrow$ RemoveSegmentResponseListAudiencesResponse $\rightarrow$ ListSegmentsResponseAudience $\rightarrow$ SegmentTo interact with the Resend API, you must first create a Client. You can use the standard constructor NewClient which uses a default HTTP client, or NewCustomClient if you need to provide your own *http.Client (e.g., for custom timeouts or proxy settings).
Note that the client uses the RESEND_BASE_URL environment variable if you need to point to a different base URL, defaulting to https://api.resend.com/.
import "github.com/resend/resend-go/v4"
// Using the default constructor
client := resend.NewClient("re_123456789")
// Using a custom HTTP client
customHTTPClient := &http.Client{
Timeout: 30 * time.Second,
}
client := resend.NewCustomClient(customHTTPClient, "re_123456789")To send an email, initialize a client using resend.NewClient(apiKey) and call the client.Emails.Send method with a *resend.SendEmailRequest object.
Fields available in SendEmailRequest include:
To: A slice of recipient email addresses ([]string).From: The sender's email address (string).Subject: The email subject line (string).Text: The plain text body of the email (string).Cc: A slice of CC email addresses ([]string).Bcc: A slice of BCC email addresses ([]string).ReplyTo: The email address to reply to (string).The Send method returns the sent email object (containing the Id) and an error.
package main
import (
"fmt"
"github.com/resend/resend-go/v4"
)
func main() {
apiKey := "re_123"
client := resend.NewClient(apiKey)
params := &resend.SendEmailRequest{
To: []string{"to@example", "you@example.com"},
From: "me@exemple.io",
Text: "hello world",
Subject: "Hello from Golang",
Cc: []string{"cc@example.com"},
Bcc: []string{"cc@example.com"},
ReplyTo: "replyto@example.com",
}
sent, err := client.Emails.Send(params)
if err != nil {
panic(err)
}
fmt.Println(sent.Id)
}When running the application via Docker Compose, you must provide your Resend API key using the RESEND_API_KEY environment variable. This value is injected into the app service.
environment:
RESEND_API_KEY: ${RESEND_API_KEY}The DomainClaimsSvc interface provides methods to claim a domain that has already been verified by another Resend account. This process allows you to take ownership of a domain within Resend.
Key operations include:
Create: Starts a new claim process.Get: Retrieves the current status and DNS records for a specific claim.Verify: Triggers the asynchronous DNS verification and ownership transfer process.Most methods have a WithContext variant for better control over request lifecycles in Go applications.
// Example usage pattern
claim, err := domainClaimsSvc.Create(ctx, &resend.CreateDomainClaimRequest{
Name: "example.com",
})
// Trigger verification
verifiedClaim, err := domainClaimsSvc.Verify(domainId)
// Poll for status
status, err := domainClaimsSvc.Get(domainId)
if status.Status == resend.DomainClaimStatusCompleted {
// Claim successful
}