Resend Go SDK

repository·main·Indexed 42 days ago

https://github.com/resend/resend-go

A 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.

Tokens
29.2K
Snippets
106
Records
131
Agent score
54%

What's inside Resend

  1. Declare template variables in CreateTemplateRequest and UpdateTemplateRequest

    main

    When 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",
            },
        },
    }
  2. Suppression origins and types

    main

    Suppressions in Resend are categorized by their SuppressionOrigin. This helps identify why an email address was added to the list.

    Available Origins:

    • SuppressionOriginBounce ("bounce"): The email bounced.
    • SuppressionOriginComplaint ("complaint"): The recipient marked the email as spam.
    • SuppressionOriginManual ("manual"): The suppression was added manually via the API.

    Data Structures:

    • 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.
  3. Configure Automation Steps and Connections

    main

    Automations are composed of AutomationStep objects and AutomationConnection objects that define the workflow logic.

    Automation Steps

    Each step has a Key, a Type, and a Config map for step-specific parameters. Supported AutomationStepType values:

    • trigger
    • send_email
    • delay
    • wait_for_event
    • condition
    • contact_update
    • contact_delete
    • add_to_segment

    Automation Connections

    Connections define how the flow moves from one step to another using From and To keys. Supported AutomationConnectionType values:

    • default
    • condition_met
    • condition_not_met
    • timeout
    • event_received
    steps := []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},
    }
  4. Configure Batch Validation Modes

    main

    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,
    }
  5. Provide Idempotency Keys for POST requests

    main
    To prevent accidental duplicate operations (like sending the same email twice) during network retries, you can pass an Options implementation that provides an idempotency key. The SDK will automatically set the Idempotency-Key header for POST requests if a key is provided.
  6. Migrate from Audiences to Segments

    main

    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$ SegmentsSvc
    • AudiencesSvcImpl $\rightarrow$ SegmentsSvcImpl
    • CreateAudienceRequest $\rightarrow$ CreateSegmentRequest
    • CreateAudienceResponse $\rightarrow$ CreateSegmentResponse
    • RemoveAudienceResponse $\rightarrow$ RemoveSegmentResponse
    • ListAudiencesResponse $\rightarrow$ ListSegmentsResponse
    • Audience $\rightarrow$ Segment
  7. Initialize the Resend Client

    main

    To 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")
  8. Send an email using the Resend Go SDK

    main

    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)
    }
  9. Configure the RESEND_API_KEY environment variable

    main

    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}
  10. Manage domain claims with DomainClaimsSvc

    main

    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
    }