### Install Resend Go SDK Source: https://github.com/resend/resend-go/blob/main/README.md Use this command to install the Resend Go SDK. Ensure you have Go installed and configured. ```bash go get github.com/resend/resend-go/v3 ``` -------------------------------- ### Example BatchEmailResponse Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/batch-emails.md Illustrates how to construct a BatchEmailResponse object, showing successful email IDs and an example error. ```go response := &resend.BatchEmailResponse{ Data: []resend.SendEmailResponse{ {Id: "email_1"}, {Id: "email_2"}, }, Errors: []resend.BatchError{ {Index: 2, Message: "Invalid email address"}, }, } ``` -------------------------------- ### Complete Resend Go Client Configuration Example Source: https://github.com/resend/resend-go/blob/main/_autodocs/configuration.md This example demonstrates initializing the Resend Go client with a custom HTTP client, setting request-level timeouts using context, and sending an email with an idempotency key. ```go package main import ( "context" "net/http" "time" "github.com/resend/resend-go/v3" ) func main() { // Create custom HTTP client transport := &http.Transport{ MaxIdleConns: 100, MaxConnsPerHost: 10, IdleConnTimeout: 90 * time.Second, } httpClient := &http.Client{ Transport: transport, Timeout: 30 * time.Second, } // Initialize client client := resend.NewCustomClient(httpClient, "re_api_key") // Use context for request-level timeout ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() // Send email with idempotency opts := &resend.SendEmailOptions{ IdempotencyKey: "email-123", } params := &resend.SendEmailRequest{ From: "hello@example.com", To: []string{"user@example.com"}, Subject: "Hello", Html: "
Test
", } sent, err := client.Emails.SendWithOptions(ctx, params, opts) if err != nil { panic(err) } println(sent.Id) } ``` -------------------------------- ### Send Batch Emails Example Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/batch-emails.md Example demonstrating how to send a batch of emails using the Batch.Send method. Ensure the client is initialized before use. Handles potential errors and iterates through successful sends. ```go emails := []*resend.SendEmailRequest{ { From: "hello@example.com", To: []string{"user1@example.com"}, Subject: "Hello User 1", Html: "Welcome
", }, { From: "hello@example.com", To: []string{"user2@example.com"}, Subject: "Hello User 2", Html: "Welcome
", }, } response, err := client.Batch.Send(emails) if err != nil { panic(err) } for _, sent := range response.Data { fmt.Println(sent.Id) } ``` -------------------------------- ### Attachment Structure and Examples Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/emails.md Defines the structure for file attachments in emails. Provides examples for creating attachments using binary content or a URL path. ```go type Attachment struct { Content []byte Filename string Path string ContentType string ContentId string InlineContentId string } ``` ```go attachment := &resend.Attachment{ Filename: "document.pdf", Content: pdfBytes, ContentType: "application/pdf", } attachment2 := &resend.Attachment{ Filename: "logo.png", ContentId: "logo_ref", Path: "https://example.com/images/logo.png", } ``` -------------------------------- ### Create Topic Example Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/topics.md Demonstrates how to create a new subscription topic using the Topics service. Ensure you have initialized the Resend client. ```go params := &resend.CreateTopicRequest{ Name: "Marketing Updates", DefaultSubscription: resend.DefaultSubscriptionOptIn, Description: "Receive our latest product updates", } result, err := client.Topics.Create(params) if err != nil { panic(err) } fmt.Println(result.Id) // Topic ID ``` -------------------------------- ### Example CreateApiKeyRequest Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/api-keys.md Instantiates a CreateApiKeyRequest with a name and full access permission. ```go req := &resend.CreateApiKeyRequest{ Name: "Mobile App Key", Permission: "full_access", } ``` -------------------------------- ### Example BatchSendEmailOptions Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/batch-emails.md Shows how to create a BatchSendEmailOptions object with a specified idempotency key and permissive validation mode. ```go opts := &resend.BatchSendEmailOptions{ IdempotencyKey: "batch-id-123", BatchValidation: resend.BatchValidationPermissive, } ``` -------------------------------- ### Create Contact Example Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/contacts.md Demonstrates how to create a new contact with specified email, name, and custom properties. Ensure the Resend client is initialized before use. ```go params := &resend.CreateContactRequest{ Email: "john@example.com", FirstName: "John", LastName: "Doe", Unsubscribed: false, Properties: map[string]any{ "tier": "premium", "age": "30", }, } result, err := client.Contacts.Create(params) if err != nil { panic(err) } fmt.Println(result.Id) // Contact ID ``` -------------------------------- ### Create Domain Request with Capabilities Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/domains.md Example of creating a domain request, specifying the domain name and its capabilities for sending and receiving emails. ```go capabilities := &resend.DomainCapabilities{ Sending: "enabled", Receiving: "enabled", } params := &resend.CreateDomainRequest{ Name: "mail.example.com", Capabilities: capabilities, } ``` -------------------------------- ### Create Topic with Default Subscription Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/topics.md Examples demonstrating how to create a Resend topic with either default opt-in or opt-out subscription preferences for new contacts. ```go // New contacts subscribe to marketing updates by default req := &resend.CreateTopicRequest{ Name: "Marketing", DefaultSubscription: resend.DefaultSubscriptionOptIn, } // New contacts must opt-in to transactional emails req := &resend.CreateTopicRequest{ Name: "Transactional", DefaultSubscription: resend.DefaultSubscriptionOptOut, } ``` -------------------------------- ### Create Automation Workflow Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/automations.md Use this to create a new automation workflow. Provide a name, status, steps, and connections for the automation. The example demonstrates setting up a trigger and an email sending step. ```go params := &resend.CreateAutomationRequest{ Name: "Welcome Series", Status: resend.AutomationStatusEnabled, Steps: []resend.AutomationStep{ { Key: "trigger", Type: resend.AutomationStepTypeTrigger, Config: map[string]any{ "type": "contact.created", }, }, { Key: "send_welcome", Type: resend.AutomationStepTypeSendEmail, Config: map[string]any{ "template_id": "template_123", }, }, }, Connections: []resend.AutomationConnection{ { From: "trigger", To: "send_welcome", Type: resend.AutomationConnectionTypeDefault, }, }, } result, err := client.Automations.Create(params) if err != nil { panic(err) } fmt.Println(result.Id) ``` -------------------------------- ### Send Email with Resend Go SDK Source: https://github.com/resend/resend-go/blob/main/README.md This example demonstrates how to send an email using the Resend Go SDK. It requires an API key and sets up email parameters like recipients, subject, and body. ```go package main import ( "fmt" "github.com/resend/resend-go/v3" ) 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) } ``` -------------------------------- ### Create a New Segment Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/segments.md Example of how to instantiate and use the CreateSegmentRequest to create a new segment via the Resend client. ```go req := &resend.CreateSegmentRequest{ Name: "VIP Subscribers", } result, err := client.Segments.Create(req) ``` -------------------------------- ### List All API Keys Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/api-keys.md Retrieves a list of all API keys associated with the project. It returns the list of keys along with their metadata. Use this to get an overview of your existing API keys. ```go keys, err := client.ApiKeys.List() if err != nil { panic(err) } for _, key := range keys.Data { fmt.Println(key.Id, key.Name, key.CreatedAt) if key.LastUsedAt != nil { fmt.Println("Last used:", *key.LastUsedAt) } } ``` -------------------------------- ### Get Domain Details Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/domains.md Retrieves full domain details, including records and status, using the domain ID. ```go domain, err := client.Domains.Get("domain_id") if err != nil { panic(err) } fmt.Println(domain.Status) // pending, verified, failed, etc. fmt.Println(domain.Region) // Region where domain is set up ``` -------------------------------- ### Update Contact Example Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/contacts.md Demonstrates how to update a contact using the Resend Go SDK. Initializes an UpdateContactRequest with new details and calls the client's Update method. The SetUnsubscribed method should be used to set the unsubscribed field to false. ```go params := &resend.UpdateContactRequest{ Id: "contact_123", Email: "new@example.com", FirstName: "Jane", } params.SetUnsubscribed(false) // Use this method to set to false result, err := client.Contacts.Update(params) ``` -------------------------------- ### TemplateVariable Definition and Example Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/templates.md Defines a variable that can be used within email templates. The example shows how to define string and number variables with fallback values. ```go type TemplateVariable struct { Key string Type VariableType FallbackValue any } ``` ```go vars := []*resend.TemplateVariable{ { Key: "firstName", Type: resend.VariableTypeString, FallbackValue: "User", }, { Key: "discount", Type: resend.VariableTypeNumber, FallbackValue: 0, }, } ``` -------------------------------- ### Get Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/templates.md Retrieves a specific email template by its identifier. ```APIDOC ## Get ### Description Retrieves a specific email template by its identifier. ### Method GET ### Endpoint /templates/{identifier} ### Parameters #### Path Parameters - **identifier** (string) - Required - The unique identifier of the template. ### Response #### Success Response (200) - **Id** (string) - The ID of the template. - **Name** (string) - The name of the template. - **Alias** (string) - The alias of the template. - **Subject** (string) - The subject of the template. - **Html** (string) - The HTML content of the template. - **Text** (string) - The plain text content of the template. - **Variables** ([]TemplateVariable) - The list of variables used in the template. - **CreatedAt** (string) - The creation timestamp of the template. - **UpdatedAt** (string) - The last update timestamp of the template. - **PublishedAt** (string) - The publication timestamp of the template. - **Object** (string) - The object type, which is 'template'. #### Response Example ```json { "Id": "tpl_xxxxxxxxxxxxxxxx", "Name": "Welcome Email", "Alias": "welcome", "Subject": "Welcome, {{{firstName}}}!", "Html": "Hello {{{firstName}}} {{{lastName}}}
", "Text": "Hello {{{firstName}}} {{{lastName}}}", "Variables": [ { "Key": "firstName", "Type": "string", "FallbackValue": "User" }, { "Key": "lastName", "Type": "string", "FallbackValue": "Name" } ], "CreatedAt": "2023-10-26T10:00:00Z", "UpdatedAt": "2023-10-26T10:00:00Z", "PublishedAt": "2023-10-26T10:00:00Z", "Object": "template" } ``` ``` -------------------------------- ### Initialize Resend Client with Default Configuration Source: https://github.com/resend/resend-go/blob/main/_autodocs/configuration.md Use `NewClient` for basic initialization with default HTTP settings. Requires only your API key. ```go client := resend.NewClient("re_your_api_key") ``` -------------------------------- ### Get Email Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/emails.md Retrieves a specific email by its unique identifier. ```APIDOC ## Get Email ### Description Retrieves a specific email by its unique identifier. ### Method `Get` ### Parameters #### Path Parameters - **emailId** (string) - Required - The unique identifier of the email to retrieve. ### Response #### Success Response - **Email** (*Email) - The email object. - **error** (error) - An error object if the operation fails. ``` -------------------------------- ### Get Automation Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/automations.md Retrieves a specific automation workflow by its ID. ```APIDOC ## Get Automation ### Description Retrieves an automation workflow. ### Method Not applicable (SDK method) ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters - **automationId** (string) - Required - Automation ID #### Query Parameters None #### Request Body None ### Request Example (Request example not provided in source) ### Response #### Success Response - **Automation object** - The automation object with all its details. #### Response Example (Response details not explicitly provided in source, only return type is mentioned as *Automation) ``` -------------------------------- ### Get Webhook Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/webhooks.md Retrieves a specific webhook by its unique identifier. ```APIDOC ## Get Webhook ### Description Retrieves a webhook by ID. ### Method GET ### Endpoint /webhooks/{webhookId} ### Parameters #### Path Parameters - **webhookId** (string) - Required - Webhook ID ### Response #### Success Response (200) - **Webhook** (*Webhook) - Webhook object with all details ``` -------------------------------- ### List Webhooks Go Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/webhooks.md Lists all webhooks in the project. Requires a client instance. ```go webhooks, err := client.Webhooks.List() if err != nil { panic(err) } for _, hook := range webhooks.Data { fmt.Println(hook.Id, hook.Endpoint, hook.Status) } ``` -------------------------------- ### Get Topic Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/topics.md Retrieves a specific subscription topic by its ID. ```APIDOC ## Get Topic ### Description Retrieves a specific subscription topic by its ID. ### Method GET ### Endpoint /topics/{topicId} ### Parameters #### Path Parameters - **topicId** (string) - Required - The ID of the topic to retrieve. ### Response #### Success Response (200) - **Topic** (*Topic) - The retrieved topic object. - **Id** (string) - The unique identifier for the topic. - **Name** (string) - The name of the topic. - **DefaultSubscription** (string) - The default subscription status. - **Description** (string) - A description of the topic. - **CreatedAt** (string) - The timestamp when the topic was created. #### Response Example ```json { "Id": "topic_12345abcde", "Name": "Marketing Updates", "DefaultSubscription": "OPT_IN", "Description": "Receive our latest product updates", "CreatedAt": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Get Segment Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/segments.md Retrieves a specific segment by its unique identifier. ```APIDOC ## Get Segment ### Description Retrieves a segment by ID. ### Method Signature ```go func (s *SegmentsSvcImpl) Get(segmentId string) (Segment, error) ``` ### Parameters #### Path Parameters - **segmentId** (string) - Required - Segment ID ### Returns - **Segment** - Segment object - **error** - Error if retrieval fails ``` -------------------------------- ### Get Segment Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/segments.md Retrieves a specific contact segment by its ID. ```APIDOC ## Get Segment ### Description Retrieves a specific contact segment by its ID. ### Method GET ### Endpoint /segments/{segmentId} ### Parameters #### Path Parameters - **segmentId** (string) - yes - The ID of the segment to retrieve. ### Response #### Success Response (200) - **id** (string) - The ID of the segment. - **name** (string) - The name of the segment. - **created_at** (string) - The timestamp when the segment was created. ``` -------------------------------- ### Initialize Resend Client with Custom HTTP Client Source: https://github.com/resend/resend-go/blob/main/_autodocs/configuration.md Use `NewCustomClient` to provide a fully customized `http.Client`. This allows control over timeouts, transports, and other HTTP behaviors. ```go httpClient := &http.Client{ Timeout: 30 * time.Second, Transport: &http.Transport{ MaxIdleConns: 100, MaxConnsPerHost: 10, }, } client := resend.NewCustomClient(httpClient, "re_api_key") ``` -------------------------------- ### Get Email Attachment Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/emails.md Retrieves a specific attachment of an email by its unique identifiers. ```APIDOC ## Get Email Attachment ### Description Retrieves a specific attachment of an email by its unique identifiers. ### Method `GetAttachment` ### Parameters #### Path Parameters - **emailId** (string) - Required - The unique identifier of the email. - **attachmentId** (string) - Required - The unique identifier of the attachment. ### Response #### Success Response - **EmailAttachment** (*EmailAttachment) - The email attachment object. - **error** (error) - An error object if the operation fails. ``` -------------------------------- ### Get Email Attachment with Context Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/emails.md Retrieves a specific attachment of an email with a provided context. ```APIDOC ## Get Email Attachment with Context ### Description Retrieves a specific attachment of an email with a provided context. ### Method `GetAttachmentWithContext` ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - The context for the request. - **emailId** (string) - Required - The unique identifier of the email. - **attachmentId** (string) - Required - The unique identifier of the attachment. ### Response #### Success Response - **EmailAttachment** (*EmailAttachment) - The email attachment object. - **error** (error) - An error object if the operation fails. ``` -------------------------------- ### List Domains with Options Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/domains.md Use this method to list domains with pagination options. The `options` parameter allows for controlling the number of results and pagination tokens. ```go func (s *DomainsSvcImpl) ListWithOptions(ctx context.Context, options *ListOptions) (ListDomainsResponse, error) ``` -------------------------------- ### Default HTTP Client Initialization Source: https://github.com/resend/resend-go/blob/main/_autodocs/configuration.md Initializes the default HTTP client with a 1-minute timeout. This client is used when no custom client is provided. ```go var defaultHTTPClient = &http.Client{ Timeout: time.Minute, } ``` -------------------------------- ### Get Email with Context Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/emails.md Retrieves a specific email by its unique identifier with a provided context. ```APIDOC ## Get Email with Context ### Description Retrieves a specific email by its unique identifier with a provided context. ### Method `GetWithContext` ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - The context for the request. - **emailId** (string) - Required - The unique identifier of the email to retrieve. ### Response #### Success Response - **Email** (*Email) - The email object. - **error** (error) - An error object if the operation fails. ``` -------------------------------- ### List All Domains Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/domains.md Lists all domains in the project, returning a paginated response. Iterates through the data to print domain names and statuses. ```go domains, err := client.Domains.List() if err != nil { panic(err) } for _, domain := range domains.Data { fmt.Println(domain.Name, domain.Status) } ``` -------------------------------- ### Pagination with ListOptions Source: https://github.com/resend/resend-go/blob/main/_autodocs/README.md Configure pagination for list methods using ListOptions to specify the number of results per page and a cursor for subsequent requests. ```go opts := &resend.ListOptions{ Limit: intPtr(50), After: stringPtr("cursor"), } emails, err := client.Emails.ListWithOptions(ctx, opts) ``` -------------------------------- ### Get Automation Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/automations.md Retrieves a specific automation campaign by its ID. Use this to fetch details of an existing automation. ```APIDOC ## Get Automation ### Description Retrieves a specific automation campaign by its ID. ### Method GET ### Endpoint /automations/{automationId} ### Parameters #### Path Parameters - **automationId** (string) - Required - The ID of the automation to retrieve. ``` -------------------------------- ### Get Domain Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/domains.md Retrieves the details of a specific domain using its ID. Includes DNS records and status. ```APIDOC ## Get Domain ### Description Retrieves domain details. ### Method Signature func (s *DomainsSvcImpl) Get(domainId string) (Domain, error) ### Parameters #### Path Parameters - **domainId** (string) - Required - Domain ID ### Returns - **Domain** - Full domain object with records and status - **error** - An error if the domain retrieval fails ### Example ```go domain, err := client.Domains.Get("domain_id") if err != nil { panic(err) } fmt.Println(domain.Status) // pending, verified, failed, etc. fmt.Println(domain.Region) // Region where domain is set up ``` ``` -------------------------------- ### Client Initialization and Fields Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/client-and-initialization.md The main entry point for the Resend Go SDK. All API operations are accessed through this client instance. It provides access to various services for interacting with the Resend API. ```APIDOC ## Client The main entry point for the Resend Go SDK. All API operations are accessed through this client instance. ### Fields - **ApiKey** (string) - API authentication token from Resend dashboard - **BaseURL** (*url.URL) - Base URL for API requests (defaults to https://api.resend.com/) - **UserAgent** (string) - User agent header sent with requests - **Emails** (*EmailsSvcImpl) - Service for email operations - **Batch** (BatchSvc) - Service for batch email operations - **ApiKeys** (ApiKeysSvc) - Service for API key management - **Domains** (DomainsSvc) - Service for domain management - **Segments** (SegmentsSvc) - Service for segment operations - **Audiences** (AudiencesSvc) - Deprecated alias for Segments - **Contacts** (*ContactsSvcImpl) - Service for contact management - **ContactProperties** (ContactPropertiesSvc) - Service for contact properties - **Broadcasts** (BroadcastsSvc) - Service for broadcast operations - **Templates** (TemplatesSvc) - Service for email template operations - **Topics** (TopicsSvc) - Service for topic management - **Webhooks** (WebhooksSvc) - Service for webhook management - **Logs** (LogsSvc) - Service for email log operations - **Automations** (AutomationsSvc) - Service for automation workflows - **Events** (EventsSvc) - Service for custom event operations ``` -------------------------------- ### Remove Contact Go Example Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/contacts.md Use this to delete a contact from your Resend account. Ensure you have the correct contact ID. ```go options := &resend.RemoveContactOptions{ Id: "contact_id", } result, err := client.Contacts.Remove(options) if err != nil { panic(err) } fmt.Println(result.Deleted) // true if successful ``` -------------------------------- ### Create HTTP Request with Options Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/client-and-initialization.md Creates an HTTP request with additional options, such as idempotency keys. Use this when advanced request configurations are needed. ```go func (c *Client) NewRequestWithOptions(ctx context.Context, method, path string, params any, options Options) (*http.Request, error) ``` ```go opts := &resend.SendEmailOptions{ IdempotencyKey: "unique-key-123", } req, err := client.NewRequestWithOptions(ctx, "POST", "emails", emailParams, opts) ``` -------------------------------- ### Passing Options via Struct Pointers Source: https://github.com/resend/resend-go/blob/main/_autodocs/README.md Demonstrates how to pass optional parameters to API methods using struct pointers. This is the standard way to configure requests with specific options. ```go opts := &resend.SendEmailOptions{ IdempotencyKey: "id", } ``` -------------------------------- ### GetWithContext Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/emails.md Retrieves email details with context support, allowing for cancellation and timeouts. This is an enhanced version of the Get method. ```APIDOC ## GetWithContext ### Description Retrieves email details with context support. ### Method GET (inferred from context of retrieving data, actual method not specified) ### Endpoint /emails/{emailId} (inferred from context, actual endpoint not specified) ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Context for timeout and cancellation - **emailId** (string) - Required - ID of the email to retrieve #### Query Parameters None #### Request Body None ### Request Example (Request example not provided in source) ### Response #### Success Response (200) - **Email** (*Email) - Email object with full details - **error** (error) - An error object if the email retrieval failed. #### Response Example (Response example not provided in source) ``` -------------------------------- ### Email Sending Source: https://github.com/resend/resend-go/blob/main/_autodocs/README.md Demonstrates how to initialize the Resend client and send an email using the SDK. ```APIDOC ## Send Email ### Description Sends an email using the Resend service. ### Method `Send` (Base method) `SendWithContext` (With custom context) `SendWithOptions` (With options like idempotency keys) ### Endpoint (Not explicitly defined in source, inferred from SDK usage) ### Parameters #### Request Body (`resend.SendEmailRequest`) - **From** (string) - Required - The sender's email address. - **To** (string array) - Required - A list of recipient email addresses. - **Subject** (string) - Required - The subject line of the email. - **Html** (string) - Optional - The HTML content of the email. - **Text** (string) - Optional - The plain text content of the email. - **Cc** (string array) - Optional - A list of CC recipient email addresses. - **Bcc** (string array) - Optional - A list of BCC recipient email addresses. - **ReplyTo** (string) - Optional - The email address to use for replies. - **Attachments** (array of `resend.Attachment`) - Optional - A list of attachments for the email. #### Options (`resend.SendEmailOptions`) - **IdempotencyKey** (string) - Optional - A unique key to ensure the request is processed only once. ### Request Example ```go // Using base method resp, err := client.Emails.Send(&resend.SendEmailRequest{ From: "hello@example.com", To: []string{"user@example.com"}, Subject: "Hello World", Html: "This is a test email
", }) // Using SendWithOptions opts := &resend.SendEmailOptions{IdempotencyKey: "unique-id"} sent, err := client.Emails.SendWithOptions(ctx, params, opts) ``` ### Response #### Success Response - **Id** (string) - The unique identifier of the sent email. #### Response Example ```json { "Id": "email_id_12345" } ``` ### Error Handling Refer to the general error handling section for details on `resend.ErrRateLimit`, `resend.RateLimitError`, and validation errors. ``` -------------------------------- ### Configure Pagination with ListOptions Source: https://github.com/resend/resend-go/blob/main/_autodocs/configuration.md Use `ListOptions` to configure pagination for list operations. Set `Limit`, `After`, or `Before` cursors as needed. ```go type ListOptions struct { Limit *int After *string Before *string } ``` ```go opts := &resend.ListOptions{ Limit: intPtr(50), After: stringPtr("cursor_value"), } emails, err := client.Emails.ListWithOptions(ctx, opts) ``` -------------------------------- ### Get Broadcast Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/broadcasts.md Retrieves a specific broadcast campaign by its ID. This method returns the full details of a single broadcast. ```APIDOC ## Get Broadcast ### Description Retrieves a broadcast campaign by its unique identifier. ### Method GET ### Endpoint /broadcasts/{broadcastId} ### Parameters #### Path Parameters - **broadcastId** (string) - Required - The ID of the broadcast campaign to retrieve. ### Response #### Success Response (200) - **Broadcast** (*Broadcast) - An object containing the full details of the broadcast campaign. ### Response Example ```json { "id": "clx0z7f7a000008l4g9h0j1k2", "name": "Summer Sale", "status": "draft", "created_at": "2024-01-01T12:00:00Z", "updated_at": "2024-01-01T12:00:00Z" } ``` ``` -------------------------------- ### Get Specific Automation Run Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/automations.md Retrieves detailed information about a specific automation run, including its status and executed steps. ```APIDOC ## Get Specific Automation Run ### Description Retrieves details of a specific automation run. ### Method GET ### Endpoint /automations/{automationId}/runs/{runId} ### Parameters #### Path Parameters - **automationId** (string) - Required - Automation ID - **runId** (string) - Required - Run ID ### Response #### Success Response (200) - **status** (string) - The status of the automation run - **executedSteps** (array) - Details of the steps executed during the run #### Response Example ```json { "status": "completed", "executedSteps": [ { "stepName": "Step 1", "status": "success" }, { "stepName": "Step 2", "status": "success" } ] } ``` ``` -------------------------------- ### Accessing Resend Services Source: https://github.com/resend/resend-go/blob/main/_autodocs/configuration.md After creating a client with an API key, all services are automatically configured and ready for use. This includes direct services and nested services. ```go client := resend.NewClient("re_api_key") // All services are ready immediately client.Emails // EmailsSvc client.Contacts // ContactsSvc client.Templates // TemplatesSvc client.Domains // DomainsSvc client.Topics // TopicsSvc client.Webhooks // WebhooksSvc client.ApiKeys // ApiKeysSvc client.Segments // SegmentsSvc client.Batch // BatchSvc client.Broadcasts // BroadcastsSvc client.Automations // AutomationsSvc client.Events // EventsSvc client.Logs // LogsSvc // Nested services client.Emails.Receiving // ReceivingSvc client.Contacts.Topics // ContactTopicsSvc client.Contacts.Segments // ContactSegmentsSvc client.Contacts.Properties // ContactPropertiesSvc client.Contacts.Imports // ContactImportsSvc ``` -------------------------------- ### Get Automation Run Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/automations.md Retrieves details of a specific run for an automation campaign. Use this to inspect the outcome of a particular execution. ```APIDOC ## Get Automation Run ### Description Retrieves details of a specific run for an automation campaign. ### Method GET ### Endpoint /automations/{automationId}/runs/{runId} ### Parameters #### Path Parameters - **automationId** (string) - Required - The ID of the automation. - **runId** (string) - Required - The ID of the run to retrieve. ``` -------------------------------- ### Listing Emails with Options Source: https://github.com/resend/resend-go/blob/main/_autodocs/README.md Demonstrates how to list emails with pagination options. ```APIDOC ## List Emails with Options ### Description Retrieves a list of emails with support for pagination. ### Method `ListWithOptions` ### Endpoint (Not explicitly defined in source, inferred from SDK usage) ### Parameters #### Query Parameters (`resend.ListOptions`) - **Limit** (int) - Optional - The maximum number of results to return per page. - **After** (string) - Optional - A cursor for fetching the next page of results. ### Request Example ```go opts := &resend.ListOptions{ Limit: intPtr(50), After: stringPtr("cursor"), } emails, err := client.Emails.ListWithOptions(ctx, opts) ``` ### Response #### Success Response - **Emails** (array) - A list of email objects. - **HasMore** (bool) - Indicates if there are more results available. #### Response Example ```json { "Emails": [ { "Id": "email_id_1", "From": "sender@example.com", "To": ["recipient@example.com"], "Subject": "Test Email 1" }, { "Id": "email_id_2", "From": "sender@example.com", "To": ["recipient@example.com"], "Subject": "Test Email 2" } ], "HasMore": true } ``` ``` -------------------------------- ### Email Sending Variants Source: https://github.com/resend/resend-go/blob/main/_autodocs/README.md Demonstrates the three variants for sending emails: base method, WithContext, and WithOptions. The WithOptions variant allows for additional configurations like idempotency keys. ```go sent, err := client.Emails.Send(params) ``` ```go sent, err := client.Emails.SendWithContext(ctx, params) ``` ```go opts := &resend.SendEmailOptions{IdempotencyKey: "unique-id"} sent, err := client.Emails.SendWithOptions(ctx, params, opts) ``` -------------------------------- ### Get Segment by ID in Go Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/segments.md Retrieves a specific segment using its unique identifier. Ensure you have the segment ID available. ```go segment, err := client.Segments.Get("segment_id") if err != nil { panic(err) } fmt.Println(segment.Name) fmt.Println(segment.CreatedAt) ``` -------------------------------- ### Create API Key Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/api-keys.md Creates a new API key for your Resend project. Store the returned token immediately as it is only available at creation time. Requires the 'resend' package. ```go params := &resend.CreateApiKeyRequest{ Name: "Production API Key", Permission: "full_access", } result, err := client.ApiKeys.Create(params) if err != nil { panic(err) } // IMPORTANT: Store the token safely fmt.Println("API Key ID:", result.Id) fmt.Println("Token:", result.Token) // Save this securely! ``` -------------------------------- ### Custom HTTP Client with Timeout Source: https://github.com/resend/resend-go/blob/main/_autodocs/configuration.md Creates a custom HTTP client with a specific timeout (e.g., 30 seconds) and uses it to initialize a Resend client. ```go httpClient := &http.Client{ Timeout: 30 * time.Second, // 30 second timeout } client := resend.NewCustomClient(httpClient, "re_api_key") ``` -------------------------------- ### Get Contact Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/contacts.md Retrieves a contact by email or ID. It allows fetching a specific contact's details using provided options. ```APIDOC ## Get Contact ### Description Retrieves a contact by email or ID. It allows fetching a specific contact's details using provided options. ### Method Not specified (likely SDK method call) ### Endpoint Not specified ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go options := &resend.GetContactOptions{ Id: "john@example.com", // AudienceId: "audience_id", // optional for audience-scoped contacts } contact, err := client.Contacts.Get(options) if err != nil { panic(err) } fmt.Println(contact.Email) fmt.Println(contact.FirstName) ``` ### Response #### Success Response - **Contact** (object) - Full contact object #### Response Example (Response structure not explicitly defined in source, but implies a Contact object with fields like Email and FirstName) ``` -------------------------------- ### Send Email with Options (Go) Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/emails.md Use this function to send an email with additional request options, such as an idempotency key for ensuring unique requests. The `options` parameter is optional. ```go options := &resend.SendEmailOptions{ IdempotencyKey: "unique-email-id-123", } sent, err := client.Emails.SendWithOptions(ctx, params, options) ``` -------------------------------- ### Configuring Batch Email Options Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/batch-emails.md Demonstrates how to set the BatchValidation mode when creating options for sending batch emails. Use Strict for all-or-nothing validation or Permissive for partial success. ```go // Strict mode (default) - all or nothing opts := &resend.BatchSendEmailOptions{ BatchValidation: resend.BatchValidationStrict, } // Permissive mode - partial success allowed opts := &resend.BatchSendEmailOptions{ BatchValidation: resend.BatchValidationPermissive, } // Validate mode before using if opts.BatchValidation.IsValid() { // Safe to use } ``` -------------------------------- ### NewRequest Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/client-and-initialization.md Creates an HTTP request for API calls with automatic authentication header setup. This method is used for standard API interactions. ```APIDOC ## NewRequest Creates an HTTP request for API calls with automatic authentication header setup. ### Signature ```go func (c *Client) NewRequest(ctx context.Context, method, path string, params any) (*http.Request, error) ``` ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Context for request timeout and cancellation - **method** (string) - Required - HTTP method (GET, POST, PATCH, DELETE, etc.) - **path** (string) - Required - API endpoint path (relative to base URL) - **params** (any) - Optional - Request body parameters (marshaled to JSON) ### Returns - `*http.Request` — Configured HTTP request - `error` — Error if request creation failed ### Throws - Error if JSON marshaling fails - Error if URL parsing fails ### Example ```go ctx := context.Background() req, err := client.NewRequest(ctx, "POST", "emails", &resend.SendEmailRequest{ From: "hello@example.com", To: []string{"user@example.com"}, Subject: "Hello", }) if err != nil { panic(err) } ``` ``` -------------------------------- ### ListOptions for Pagination Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/client-and-initialization.md Use ListOptions to specify pagination parameters such as the maximum number of results to return, or cursors for fetching results before or after a specific point. This is useful for paginating through lists of resources. ```go type ListOptions struct { Limit *int After *string Before *string } ``` ```go opts := &resend.ListOptions{ Limit: intPtr(50), After: stringPtr("cursor_id"), } emails, err := client.Emails.ListWithOptions(ctx, opts) ``` -------------------------------- ### Get Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/emails.md Retrieves details of a previously sent email using its unique identifier. This method is useful for checking the status or content of an email after it has been sent. ```APIDOC ## Get ### Description Retrieves details of a previously sent email. ### Method GET (inferred from context of retrieving data, actual method not specified) ### Endpoint /emails/{emailId} (inferred from context, actual endpoint not specified) ### Parameters #### Path Parameters - **emailId** (string) - Required - ID of the email to retrieve #### Query Parameters None #### Request Body None ### Request Example ```go email, err := client.Emails.Get("email_id_here") if err != nil { panic(err) } fmt.Println(email.Subject) // Email subject fmt.Println(email.From) // Sender email ``` ### Response #### Success Response (200) - **Email** (*Email) - Email object with full details - **error** (error) - An error object if the email retrieval failed. #### Response Example (Response example not provided in source) ``` -------------------------------- ### Create Topic Request Structure Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/topics.md Defines the structure for creating a new topic. The 'Name' and 'DefaultSubscription' fields are required. 'DefaultSubscription' can be 'opt_in' or 'opt_out'. ```go type CreateTopicRequest struct { Name string DefaultSubscription DefaultSubscription Description string } ``` ```go req := &resend.CreateTopicRequest{ Name: "Weekly Newsletter", DefaultSubscription: resend.DefaultSubscriptionOptIn, Description: "Subscribe to receive our weekly newsletter", } ``` -------------------------------- ### Get Specific Automation Run Details Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/automations.md Retrieves detailed information about a specific automation run. Requires both the automation ID and the run ID. ```Go run, err := client.Automations.GetRun("automation_id", "run_id") if err != nil { panic(err) } fmt.Println(run.Status) fmt.Println(run.ExecutedSteps) ``` -------------------------------- ### Get Template Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/templates.md Retrieves a specific email template by its unique identifier (ID or alias). This is useful for fetching template details for display or further processing. ```APIDOC ## Get Template ### Description Retrieves a template by ID or alias. ### Method ```go func (s *TemplatesSvcImpl) Get(identifier string) (*Template, error) ``` ### Parameters #### Path Parameters - **identifier** (string) - Required - Template ID or alias ### Returns `(*Template, error)` — Full template object with all fields ### Example ```go template, err := client.Templates.Get("welcome") if err != nil { panic(err) } fmt.Println(template.Name) fmt.Println(template.Status) // "draft" or "published" ``` ``` -------------------------------- ### List API Keys with Options Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/api-keys.md Lists API keys with support for pagination options. Allows specifying context and pagination parameters. ```APIDOC ## List API Keys with Options ### Description Lists API keys with pagination options. ### Method GET ### Endpoint /api-keys ### Parameters #### Query Parameters - **limit** (int) - Optional - Number of API keys to return. - **offset** (int) - Optional - The number of API keys to skip before starting to collect the result set. ### Request Example ```json { "limit": 10, "offset": 0 } ``` ### Response #### Success Response (200) - **data** (array) - List of API keys. - **id** (string) - The unique identifier of the API key. - **name** (string) - The name of the API key. - **created_at** (string) - The timestamp when the API key was created. - **last_used_at** (string) - The timestamp when the API key was last used (nullable). - **next_offset** (int) - The offset for the next page of results. ### Response Example ```json { "data": [ { "id": "key_abc123", "name": "My Test Key", "created_at": "2023-10-26T10:00:00Z", "last_used_at": "2023-10-26T11:00:00Z" } ], "next_offset": 10 } ``` ``` -------------------------------- ### Retrieve Automation Workflow Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/automations.md Use this to get details of an existing automation workflow by its ID. Ensure you have the correct automation ID before making the request. ```go result, err := client.Automations.Get(automationId) if err != nil { panic(err) } fmt.Println(result) ``` -------------------------------- ### List Segments with Options in Go Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/segments.md Lists segments with support for pagination options. Use this for managing large numbers of segments efficiently. ```go func (s *SegmentsSvcImpl) ListWithOptions(ctx context.Context, options *ListOptions) (ListSegmentsResponse, error) ``` -------------------------------- ### Context-Based Timeout for Requests Source: https://github.com/resend/resend-go/blob/main/_autodocs/configuration.md Demonstrates setting a per-request timeout using `context.WithTimeout`. This context-based timeout takes precedence over the HTTP client's timeout. ```go ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() sent, err := client.Emails.SendWithContext(ctx, params) ``` -------------------------------- ### Email Object Structure Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/emails.md Defines the complete structure of an email object as returned by the Get API. Includes details from recipients to content and last event. ```go type Email struct { Id string Object string To []string From string CreatedAt string Subject string Html string Text string Bcc []string Cc []string ReplyTo []string LastEvent string } ``` -------------------------------- ### Send Batch Emails with Context (Go) Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/batch-emails.md Use this method to send a batch of emails with support for context, allowing for timeout and cancellation. Ensure a context is provided for managing the request lifecycle. ```go ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() response, err := client.Batch.SendWithContext(ctx, emails) ``` -------------------------------- ### SegmentsSvc Interface Definition Source: https://github.com/resend/resend-go/blob/main/_autodocs/api-reference/segments.md Defines the methods available for interacting with the Segments service, including create, list, get, and remove operations, with and without context. ```go type SegmentsSvc interface { Create(params *CreateSegmentRequest) (CreateSegmentResponse, error) CreateWithContext(ctx context.Context, params *CreateSegmentRequest) (CreateSegmentResponse, error) List() (ListSegmentsResponse, error) ListWithContext(ctx context.Context) (ListSegmentsResponse, error) ListWithOptions(ctx context.Context, options *ListOptions) (ListSegmentsResponse, error) Get(segmentId string) (Segment, error) GetWithContext(ctx context.Context, segmentId string) (Segment, error) Remove(segmentId string) (RemoveSegmentResponse, error) RemoveWithContext(ctx context.Context, segmentId string) (RemoveSegmentResponse, error) } ```