sendlix

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 27, 2025 License: Apache-2.0 Imports: 11 Imported by: 0

README

Sendlix Go SDK

The official Go SDK for the Sendlix email service API. This SDK provides a comprehensive interface for sending emails, managing email groups, and handling authentication with the Sendlix platform.

Features

  • Email Sending: Send individual emails with full control over recipients, content, and formatting
  • Group Management: Manage email groups for efficient bulk email operations
  • Multiple Content Types: Support for HTML, plain text, and EML format emails
  • Advanced Features: Email scheduling, attachments, tracking, and categorization
  • Authentication: Automatic JWT token management with API key authentication
  • Error Handling: Comprehensive error reporting and quota information
  • Context Support: Full support for Go contexts including timeouts and cancellation

Installation

go get github.com/sendlix/go-sdk

Quick Start

package main

import (
    "context"
    "log"

    "github.com/sendlix/go-sdk/pkg"
)

func main() {
    // Create authentication with your API key
    auth, err := sendlix.NewAuth("your-secret.your-key-id")
    if err != nil {
        log.Fatal(err)
    }

    // Create an email client
    client, err := sendlix.NewEmailClient(auth, nil)
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    // Send a simple email
    response, err := client.SendEmail(context.Background(), sendlix.MailOptions{
        From:    sendlix.EmailAddress{Email: "sender@example.com", Name: "Sender Name"},
        To:      []sendlix.EmailAddress{{Email: "recipient@example.com", Name: "Recipient"}},
        Subject: "Hello from Sendlix!",
        Content: sendlix.MailContent{
            HTML: "<h1>Hello World!</h1><p>This is a test email.</p>",
            Text: "Hello World!\n\nThis is a test email.",
        },
    }, nil)

    if err != nil {
        log.Fatal(err)
    }

    log.Printf("Email sent! Message IDs: %v", response.MessageList)
    log.Printf("Emails remaining: %d", response.EmailsLeft)
}

Authentication

All API operations require authentication using an API key from your Sendlix account. The API key format is secret.keyID:

auth, err := sendlix.NewAuth("your-secret.123456")
if err != nil {
    log.Fatal(err)
}

The SDK automatically handles JWT token exchange and caching, so you don't need to manage tokens manually.

Sending Emails

Individual Emails

Send emails to specific recipients with full control over all parameters:

response, err := client.SendEmail(ctx, sendlix.MailOptions{
    From:    sendlix.EmailAddress{Email: "from@example.com", Name: "Sender Name"},
    To:      []sendlix.EmailAddress{{Email: "to@example.com", Name: "Recipient"}},
    CC:      []sendlix.EmailAddress{{Email: "cc@example.com"}},
    BCC:     []sendlix.EmailAddress{{Email: "bcc@example.com"}},
    Subject: "Important Message",
    ReplyTo: &sendlix.EmailAddress{Email: "reply@example.com"},
    Content: sendlix.MailContent{
        HTML:     "<h1>HTML Content</h1><p>This is HTML content.</p>",
        Text:     "Text Content\n\nThis is plain text content.",
        Tracking: true,
    },
}, &sendlix.AdditionalOptions{
    Category: "newsletter",
    SendAt:   &futureTime,
    Attachments: []sendlix.Attachment{{
        ContentURL:  "https://example.com/document.pdf",
        Filename:    "document.pdf",
        ContentType: "application/pdf",
    }},
})
Group Emails

Send emails to predefined groups for bulk operations:

response, err := client.SendGroupEmail(ctx, sendlix.GroupMailData{
    GroupID: "newsletter-subscribers",
    From:    sendlix.EmailAddress{Email: "news@example.com", Name: "Newsletter"},
    Subject: "Weekly Newsletter",
    Content: sendlix.MailContent{
        HTML: "<h1>This Week's News</h1><p>Stay updated with our latest news.</p>",
        Text: "This Week's News\n\nStay updated with our latest news.",
    },
    Category: "newsletter",
})
EML Format Emails

Send pre-formatted EML messages:

emlContent := []byte(`From: sender@example.com
To: recipient@example.com
Subject: Test Email

This is a test email message.`)

response, err := client.SendEMLEmail(ctx, emlContent, nil)

Group Management

Manage email groups for bulk operations:

// Create a group client
groupClient, err := sendlix.NewGroupClient(auth, nil)
if err != nil {
    log.Fatal(err)
}
defer groupClient.Close()

// Add emails to a group
emails := []sendlix.EmailData{
    {Email: "user1@example.com", Name: "User One"},
    {Email: "user2@example.com", Name: "User Two"},
}

substitutions := map[string]string{
    "company": "Example Corp",
    "product": "Amazing Product",
}

response, err := groupClient.InsertEmailToGroup(ctx, "my-group", emails, substitutions)
if err != nil {
    log.Fatal(err)
}

// Remove an email from a group
removeResponse, err := groupClient.RemoveEmailFromGroup(ctx, "my-group", "user1@example.com")

// Check if an email exists in a group
checkResponse, err := groupClient.CheckEmailInGroup(ctx, "my-group", "user2@example.com")
if err != nil {
    log.Fatal(err)
}
if checkResponse.Exists {
    log.Println("Email is in the group")
}

Configuration

Customize client behavior with configuration options:

config := &sendlix.ClientConfig{
    ServerAddress: "api.sendlix.com:443",
    UserAgent:     "MyApp/1.0.0",
    Insecure:      false, // Only set to true for testing
}

client, err := sendlix.NewEmailClient(auth, config)

Error Handling

The SDK provides detailed error information:

response, err := client.SendEmail(ctx, options, nil)
if err != nil {
    if strings.Contains(err.Error(), "authentication") {
        log.Println("Check your API key")
    } else if strings.Contains(err.Error(), "quota") {
        log.Println("Email quota exceeded")
    } else {
        log.Printf("Email send failed: %v", err)
    }
    return
}

log.Printf("Email sent successfully!")
log.Printf("Message IDs: %v", response.MessageList)
log.Printf("Emails remaining: %d", response.EmailsLeft)

Context Support

All operations support Go contexts for timeout and cancellation:

// Set a timeout for the operation
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

response, err := client.SendEmail(ctx, options, nil)

Best Practices

  1. Resource Management: Always call Close() on clients when done to prevent resource leaks
  2. Client Reuse: Reuse clients across multiple operations rather than creating new ones
  3. Context Usage: Use contexts with appropriate timeouts for network operations
  4. Error Handling: Handle errors appropriately and check quota information in responses
  5. Bulk Operations: Use group emails for bulk operations to improve performance
  6. Validation: Validate email addresses before sending to avoid quota waste

License

This SDK is licensed under the Apache License 2.0. See LICENSE for details.

Support

For support and questions:

Documentation

Overview

Package sendlix provides a comprehensive Go SDK for the Sendlix email service API.

The Sendlix Go SDK enables developers to integrate email sending capabilities into their Go applications with support for individual emails, group emails, and advanced features like scheduling, attachments, and email tracking.

Documentation Scope

This documentation covers only the public API of the Sendlix Go SDK. Generated protocol buffer files and internal implementation details are excluded from this documentation to provide a clean, focused developer experience.

Quick Start

To get started with the Sendlix SDK, you'll need an API key from your Sendlix account:

import "github.com/sendlix/go-sdk/pkg"

// Create authentication with your API key
auth, err := sendlix.NewAuth("your-secret.your-key-id")
if err != nil {
	log.Fatal(err)
}

// Create an email client
client, err := sendlix.NewEmailClient(auth, nil)
if err != nil {
	log.Fatal(err)
}
defer client.Close()

// Send a simple email
response, err := client.SendEmail(context.Background(), sendlix.MailOptions{
	From:    sendlix.EmailAddress{Email: "sender@example.com", Name: "Sender Name"},
	To:      []sendlix.EmailAddress{{Email: "recipient@example.com", Name: "Recipient"}},
	Subject: "Hello from Sendlix!",
	Content: sendlix.MailContent{
		HTML: "<h1>Hello World!</h1><p>This is a test email.</p>",
		Text: "Hello World!\n\nThis is a test email.",
	},
}, nil)

For more examples and advanced usage, see the individual type documentation and the official Sendlix API documentation.

Internal Packages

Note: Protocol buffer files are located in the internal/proto/ directory and follow Go's internal package conventions. These files are automatically excluded from public documentation and should not be used directly by external applications. All necessary functionality is exposed through the public API documented here.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AdditionalOptions

type AdditionalOptions struct {
	// Attachments is a list of files to attach to the email (optional)
	Attachments []Attachment

	// Category is used for email categorization and analytics (optional)
	Category string

	// SendAt schedules the email to be sent at a specific time (optional)
	// If nil, the email is sent immediately
	SendAt *time.Time
}

AdditionalOptions provides extended configuration options for email sending. These options allow for advanced features like scheduling and file attachments.

type Attachment

type Attachment struct {
	// ContentURL is the URL where the attachment content can be retrieved
	ContentURL string

	// Filename is the name that will be shown for the attachment
	Filename string

	// ContentType is the MIME type of the attachment (e.g., "application/pdf")
	ContentType string
}

Attachment represents a file attachment for email messages. Attachments are referenced by URL and include metadata for proper handling.

type Auth

type Auth struct {
	// contains filtered or unexported fields
}

Auth implements the IAuth interface for API key authentication with JWT tokens. It handles the exchange of API keys for JWT tokens and manages token caching to minimize authentication requests.

The Auth struct automatically handles token refresh when tokens expire, providing seamless authentication for long-running applications.

func NewAuth

func NewAuth(apiKey string) (*Auth, error)

NewAuth creates a new Auth instance with the provided API key. The API key must be in the format "secret.keyID" where secret is the API secret and keyID is the numeric key identifier.

This constructor establishes a gRPC connection to the authentication service and validates the API key format. The connection is used for JWT token exchanges throughout the lifetime of the Auth instance.

Parameters:

  • apiKey: API key in format "secret.keyID" (e.g., "abc123.456")

Returns:

  • *Auth: Configured authentication instance
  • error: Validation or connection error

Example:

auth, err := sendlix.NewAuth("your-secret.123456")
if err != nil {
	log.Fatal("Failed to create auth:", err)
}

Common errors:

  • Invalid API key format (missing dot separator)
  • Empty secret portion
  • Invalid key ID (non-numeric)
  • Connection failure to authentication service

func (*Auth) GetAuthHeader

func (a *Auth) GetAuthHeader(ctx context.Context) (string, string, error)

GetAuthHeader returns the authorization header for authenticated requests. This method implements the IAuth interface and handles JWT token retrieval and caching automatically.

The method first checks if a valid cached token exists. If the cached token is still valid (not expired), it returns the cached token immediately. If no valid cached token exists, it requests a new JWT token from the authentication service and caches it for future use.

Parameters:

  • ctx: Context for the authentication request

Returns:

  • string: Header key ("authorization")
  • string: Header value ("Bearer <token>")
  • error: Any error encountered during token retrieval

Example:

key, value, err := auth.GetAuthHeader(ctx)
if err != nil {
	log.Fatal("Auth failed:", err)
}
// key = "authorization", value = "Bearer eyJ..."

The returned token is automatically cached and reused until it expires, minimizing the number of authentication requests to the server.

type BaseClient

type BaseClient struct {
	// contains filtered or unexported fields
}

BaseClient provides common functionality for all API clients. It manages the gRPC connection, authentication, and common client configuration. All specific API clients (EmailClient, GroupClient, etc.) embed this type.

func NewBaseClient

func NewBaseClient(auth IAuth, config *ClientConfig) (*BaseClient, error)

NewBaseClient creates a new base client with the provided authentication and configuration. This function establishes a secure gRPC connection to the Sendlix API server and sets up automatic authentication for all requests. It is typically not called directly; instead, use the specific client constructors like NewEmailClient or NewGroupClient.

The function performs several important setup steps:

  • Validates that authentication is provided
  • Applies default configuration if none is provided
  • Establishes secure TLS connection (unless configured otherwise)
  • Sets up automatic authentication interceptor

Parameters:

  • auth: Authentication implementation (required, cannot be nil)
  • config: Client configuration (optional, uses defaults if nil)

Returns:

  • *BaseClient: Configured base client ready for use
  • error: Validation or connection error

Example:

auth, err := sendlix.NewAuth("secret.keyid")
if err != nil {
	log.Fatal(err)
}

config := sendlix.DefaultClientConfig()
config.UserAgent = "MyApp/1.0.0"

client, err := sendlix.NewBaseClient(auth, config)
if err != nil {
	log.Fatal(err)
}
defer client.Close()

Common errors:

  • nil authentication (auth parameter is required)
  • network connectivity issues
  • invalid server address in configuration
  • TLS handshake failures

func (*BaseClient) Close

func (c *BaseClient) Close() error

Close closes the gRPC connection and releases associated resources. This method should be called when the client is no longer needed to prevent resource leaks. It's safe to call Close multiple times.

Returns:

  • error: Any error encountered while closing the connection

Example:

client, err := sendlix.NewEmailClient(auth, nil)
if err != nil {
	log.Fatal(err)
}
defer client.Close() // Ensure cleanup

func (*BaseClient) GetConnection

func (c *BaseClient) GetConnection() *grpc.ClientConn

GetConnection returns the underlying gRPC connection. This method is primarily used internally by specific API clients to create their respective gRPC service clients.

Returns:

  • *grpc.ClientConn: The underlying gRPC connection

type CheckEmailInGroupResponse

type CheckEmailInGroupResponse struct {
	// Exists indicates whether the email address is present in the group
	Exists bool
}

CheckEmailInGroupResponse represents the result of checking email group membership. It provides a simple boolean result indicating whether the email exists in the group.

type ClientConfig

type ClientConfig struct {
	// ServerAddress is the address of the Sendlix API server.
	// Default: "api.sendlix.com:443"
	ServerAddress string

	// UserAgent is the user agent string sent with requests.
	// Default: "sendlix-go-sdk/1.0.0"
	UserAgent string

	// Insecure determines whether to skip TLS certificate verification.
	// Only use true for testing purposes. Default: false
	Insecure bool
}

ClientConfig holds configuration options for API clients. It defines connection parameters and client behavior settings.

func DefaultClientConfig

func DefaultClientConfig() *ClientConfig

DefaultClientConfig returns the default client configuration with sensible defaults for production use.

Returns:

  • ServerAddress: "api.sendlix.com:443"
  • UserAgent: "sendlix-go-sdk/1.0.0"
  • Insecure: false

type EmailAddress

type EmailAddress struct {
	// Email is the email address (required)
	Email string
	// Name is the optional display name for the email address
	Name string
}

EmailAddress represents an email address with an optional display name. It provides a convenient way to specify email recipients with human-readable names.

The display name is optional and when provided, creates email addresses in the format "Display Name <email@domain.com>". When omitted, only the email address is used.

func NewEmailAddress

func NewEmailAddress(addr interface{}) (*EmailAddress, error)

NewEmailAddress creates an EmailAddress from various input types. This function provides flexible email address creation from strings or existing EmailAddress values.

Supported input types:

  • string: Creates EmailAddress with Email field set, Name empty
  • EmailAddress: Returns a copy of the provided EmailAddress
  • *EmailAddress: Returns the pointer directly

Parameters:

  • addr: Email address as string, EmailAddress, or *EmailAddress

Returns:

  • *EmailAddress: Created email address
  • error: Type conversion error for unsupported input types

Example:

// From string
addr1, err := sendlix.NewEmailAddress("user@example.com")

// From EmailAddress struct
addr2, err := sendlix.NewEmailAddress(sendlix.EmailAddress{
	Email: "user@example.com",
	Name:  "User Name",
})

func (EmailAddress) String

func (e EmailAddress) String() string

String returns a properly formatted string representation of the email address. If a display name is provided, it returns "Name <email@domain.com>". Otherwise, it returns just the email address.

Returns:

  • string: Formatted email address string

Example:

addr := EmailAddress{Email: "john@example.com", Name: "John Doe"}
fmt.Println(addr.String()) // Output: "John Doe <john@example.com>"

addr2 := EmailAddress{Email: "jane@example.com"}
fmt.Println(addr2.String()) // Output: "jane@example.com"

type EmailClient

type EmailClient struct {
	*BaseClient
	// contains filtered or unexported fields
}

EmailClient provides comprehensive email sending functionality through the Sendlix API. It supports various email types including individual emails, group emails, and EML format emails. The client handles authentication, request formatting, and response parsing automatically.

EmailClient embeds BaseClient, inheriting connection management and authentication capabilities. All email operations require proper authentication through the configured IAuth implementation.

func NewEmailClient

func NewEmailClient(auth IAuth, config *ClientConfig) (*EmailClient, error)

NewEmailClient creates a new email client with the provided authentication and configuration. The client establishes a gRPC connection to the Sendlix email service and is ready for immediate use.

Parameters:

  • auth: Authentication implementation (required)
  • config: Client configuration (optional, uses defaults if nil)

Returns:

  • *EmailClient: Configured email client
  • error: Any error encountered during client creation

Example:

auth, err := sendlix.NewAuth("secret.keyid")
if err != nil {
	log.Fatal(err)
}

client, err := sendlix.NewEmailClient(auth, nil)
if err != nil {
	log.Fatal(err)
}
defer client.Close()

func (*EmailClient) SendEMLEmail

func (c *EmailClient) SendEMLEmail(ctx context.Context, emlData []byte, additional *AdditionalOptions) (*SendEmailResponse, error)

SendEMLEmail sends an email using EML (Email Message Format) data. This method allows sending pre-formatted email messages that follow the RFC 5322 standard for email message format.

EML format is useful when you have complete email messages that were previously generated or when integrating with other email systems that produce standard EML output.

Parameters:

  • ctx: Context for the request (supports cancellation and timeouts)
  • emlData: Complete EML message data as byte array
  • additional: Optional settings like scheduling and categorization

Returns:

  • *SendEmailResponse: Response containing message IDs and quota information
  • error: Parsing or sending error

Example:

emlContent := []byte(`From: sender@example.com
To: recipient@example.com
Subject: Test Email

This is a test email message.`)

response, err := client.SendEMLEmail(ctx, emlContent, nil)

The EML data should be a complete, valid email message including headers and body. Invalid EML format will result in parsing errors.

func (*EmailClient) SendEmail

func (c *EmailClient) SendEmail(ctx context.Context, options MailOptions, additional *AdditionalOptions) (*SendEmailResponse, error)

SendEmail sends an email with the specified options and returns the result. This is the primary method for sending individual emails through the Sendlix API. It validates all required fields and handles the complete send process.

The method performs comprehensive validation of email parameters including: - From email address presence - At least one recipient in To field - Subject line presence - Either HTML or text content presence

Parameters:

  • ctx: Context for the request (supports cancellation and timeouts)
  • options: Email configuration including recipients, subject, and content
  • additional: Optional advanced settings like attachments and scheduling

Returns:

  • *SendEmailResponse: Response containing message IDs and quota information
  • error: Validation or sending error

Example:

response, err := client.SendEmail(ctx, sendlix.MailOptions{
	From:    sendlix.EmailAddress{Email: "sender@example.com", Name: "Sender"},
	To:      []sendlix.EmailAddress{{Email: "recipient@example.com"}},
	Subject: "Hello World",
	Content: sendlix.MailContent{
		HTML: "<h1>Hello World</h1>",
		Text: "Hello World",
	},
}, &sendlix.AdditionalOptions{
	Category: "newsletter",
})

Common errors:

  • Missing required fields (from, to, subject, content)
  • Invalid email addresses
  • Authentication failures
  • Network connectivity issues
  • Quota exceeded

func (*EmailClient) SendGroupEmail

func (c *EmailClient) SendGroupEmail(ctx context.Context, data GroupMailData) (*SendEmailResponse, error)

SendGroupEmail sends an email to all members of a predefined group. This method is optimized for bulk email operations where recipients are managed as groups rather than individual addresses.

Group emails are useful for newsletters, announcements, and other communications sent to large numbers of recipients. The group must be created and populated before sending emails to it.

Parameters:

  • ctx: Context for the request (supports cancellation and timeouts)
  • data: Group email configuration including group ID and content

Returns:

  • *SendEmailResponse: Response containing message IDs and quota information
  • error: Validation or sending error

Example:

response, err := client.SendGroupEmail(ctx, sendlix.GroupMailData{
	GroupID: "newsletter-subscribers",
	From:    sendlix.EmailAddress{Email: "news@example.com", Name: "Newsletter"},
	Subject: "Weekly Newsletter",
	Content: sendlix.MailContent{
		HTML: "<h1>This Week's News</h1><p>...</p>",
		Text: "This Week's News\n\n...",
	},
	Category: "newsletter",
})

The group must exist and contain email addresses before calling this method. Empty groups will not generate an error but will result in zero emails sent.

type EmailData

type EmailData struct {
	// Email is the email address (required)
	Email string
	// Name is the optional display name for the email address
	Name string
}

EmailData represents email address information for group operations. This structure is used when adding or managing email addresses within groups, allowing for both the email address and an optional display name.

type GroupClient

type GroupClient struct {
	*BaseClient
	// contains filtered or unexported fields
}

GroupClient provides comprehensive group management functionality for the Sendlix API. It enables creating, managing, and manipulating email groups that can be used for bulk email operations. Groups are collections of email addresses that can be managed as a single unit for efficient mass communication.

GroupClient embeds BaseClient, inheriting connection management and authentication capabilities. All group operations require proper authentication through the configured IAuth implementation.

func NewGroupClient

func NewGroupClient(auth IAuth, config *ClientConfig) (*GroupClient, error)

NewGroupClient creates a new group management client with the provided authentication and configuration. The client establishes a gRPC connection to the Sendlix group service and is ready for immediate use.

Parameters:

  • auth: Authentication implementation (required)
  • config: Client configuration (optional, uses defaults if nil)

Returns:

  • *GroupClient: Configured group client
  • error: Any error encountered during client creation

Example:

auth, err := sendlix.NewAuth("secret.keyid")
if err != nil {
	log.Fatal(err)
}

client, err := sendlix.NewGroupClient(auth, nil)
if err != nil {
	log.Fatal(err)
}
defer client.Close()

func (*GroupClient) CheckEmailInGroup

func (c *GroupClient) CheckEmailInGroup(ctx context.Context, groupID string, email string) (*CheckEmailInGroupResponse, error)

CheckEmailInGroup checks whether a specific email address exists in a group. This method provides a simple way to verify group membership before performing other operations like sending group emails or managing subscriptions.

The check is performed efficiently on the server side and returns a boolean result indicating membership status.

Parameters:

  • ctx: Context for the request (supports cancellation and timeouts)
  • groupID: Identifier of the target group (required)
  • email: Email address to check for membership (required)

Returns:

  • *CheckEmailInGroupResponse: Result containing membership status
  • error: Validation or operation error

Example:

response, err := client.CheckEmailInGroup(ctx, "newsletter-group", "user@example.com")
if err != nil {
	log.Fatal(err)
}
if response.Exists {
	fmt.Println("Email is subscribed to the group")
} else {
	fmt.Println("Email is not in the group")
}

This method is useful for:

  • Preventing duplicate subscriptions
  • Verifying membership before group operations
  • Implementing subscription status checks
  • Building user interfaces that show group membership

Common errors:

  • Empty group ID
  • Empty email address
  • Group not found
  • Permission denied

func (*GroupClient) InsertEmailToGroup

func (c *GroupClient) InsertEmailToGroup(ctx context.Context, groupID string, emails []EmailData, substitutions map[string]string) (*InsertEmailToGroupResponse, error)

InsertEmailToGroup inserts one or multiple emails into a specified group with optional substitutions. This method allows bulk addition of email addresses to groups, making it efficient for managing large subscriber lists. Each email can have associated substitution variables for personalized group communications.

The method validates all input parameters including group ID presence and email address validity for each entry. All emails must have valid email addresses, while display names are optional.

Parameters:

  • ctx: Context for the request (supports cancellation and timeouts)
  • groupID: Identifier of the target group (required)
  • emails: Slice of email data to add to the group (required, at least one)
  • substitutions: Optional key-value pairs for email personalization

Returns:

  • *InsertEmailToGroupResponse: Operation result with success status and affected rows
  • error: Validation or operation error

Example:

emails := []sendlix.EmailData{
	{Email: "user1@example.com", Name: "User One"},
	{Email: "user2@example.com", Name: "User Two"},
}
substitutions := map[string]string{
	"company": "Example Corp",
	"product": "Amazing Product",
}

response, err := client.InsertEmailToGroup(ctx, "newsletter-group", emails, substitutions)
if err != nil {
	log.Fatal(err)
}
fmt.Printf("Added %d emails successfully\n", response.AffectedRows)

Common errors:

  • Empty group ID
  • Empty email list
  • Invalid email addresses
  • Group not found
  • Permission denied

func (*GroupClient) InsertSingleEmailToGroup

func (c *GroupClient) InsertSingleEmailToGroup(ctx context.Context, groupID string, email EmailData, substitutions map[string]string) (*InsertEmailToGroupResponse, error)

InsertSingleEmailToGroup inserts a single email into a group with optional substitutions. This is a convenience method that wraps InsertEmailToGroup for single email operations, providing a simpler interface when only one email address needs to be added.

Parameters:

  • ctx: Context for the request (supports cancellation and timeouts)
  • groupID: Identifier of the target group (required)
  • email: Email data to add to the group (required)
  • substitutions: Optional key-value pairs for email personalization

Returns:

  • *InsertEmailToGroupResponse: Operation result with success status
  • error: Validation or operation error

Example:

email := sendlix.EmailData{
	Email: "newuser@example.com",
	Name:  "New User",
}
substitutions := map[string]string{
	"welcome_bonus": "20% off",
}

response, err := client.InsertSingleEmailToGroup(ctx, "customers", email, substitutions)

func (*GroupClient) RemoveEmailFromGroup

func (c *GroupClient) RemoveEmailFromGroup(ctx context.Context, groupID string, email string) (*RemoveEmailFromGroupResponse, error)

RemoveEmailFromGroup removes a specific email address from a group. This method provides targeted removal of individual email addresses from groups, useful for handling unsubscribes or managing group membership.

The operation is idempotent - removing an email that doesn't exist in the group will not cause an error but will result in zero affected rows.

Parameters:

  • ctx: Context for the request (supports cancellation and timeouts)
  • groupID: Identifier of the target group (required)
  • email: Email address to remove from the group (required)

Returns:

  • *RemoveEmailFromGroupResponse: Operation result with success status and affected rows
  • error: Validation or operation error

Example:

response, err := client.RemoveEmailFromGroup(ctx, "newsletter-group", "user@example.com")
if err != nil {
	log.Fatal(err)
}
if response.AffectedRows > 0 {
	fmt.Println("Email successfully removed from group")
} else {
	fmt.Println("Email was not found in group")
}

Common errors:

  • Empty group ID
  • Empty email address
  • Group not found
  • Permission denied

type GroupMailData

type GroupMailData struct {
	// From specifies the sender's email address (required)
	From EmailAddress

	// GroupID identifies the recipient group (required)
	GroupID string

	// Subject is the email subject line (required)
	Subject string

	// Category is used for email categorization and analytics (optional)
	// Category is used for email categorization and analytics (optional)
	Category string

	// Content contains the email body and formatting options (required)
	Content MailContent
}

GroupMailData represents the data structure for sending emails to predefined groups. This is used for bulk email operations where recipients are managed as groups.

type IAuth

type IAuth interface {
	// GetAuthHeader returns the authentication header key and value
	// that should be included in API requests.
	//
	// Parameters:
	//   - ctx: Context for the authentication request
	//
	// Returns:
	//   - string: Header key (e.g., "authorization")
	//   - string: Header value (e.g., "Bearer token")
	//   - error: Any error encountered during authentication
	GetAuthHeader(ctx context.Context) (string, string, error)
}

IAuth defines the authentication interface that all authentication implementations must satisfy. It provides a contract for generating authentication headers required for API requests.

type InsertEmailToGroupResponse

type InsertEmailToGroupResponse struct {
	// Success indicates whether the operation completed successfully
	Success bool
	// Message provides additional details about the operation result
	Message string
	// AffectedRows indicates how many email addresses were successfully added
	AffectedRows int64
}

InsertEmailToGroupResponse represents the result of adding emails to a group. It provides detailed information about the operation's success and impact.

type MailContent

type MailContent struct {
	// HTML content of the email (optional)
	// Should contain valid HTML markup for rich formatting
	HTML string

	// Text content of the email (optional)
	// Plain text version for email clients that don't support HTML
	Text string

	// Tracking enables email tracking features such as open tracking
	// and click tracking when supported by the email service
	Tracking bool
}

MailContent represents the content and formatting options for an email message. It supports both HTML and plain text content, allowing for rich email formatting while maintaining compatibility with text-only email clients.

type MailOptions

type MailOptions struct {
	// From specifies the sender's email address (required)
	From EmailAddress

	// To contains the list of primary recipients (required, at least one)
	To []EmailAddress

	// CC contains the list of carbon copy recipients (optional)
	CC []EmailAddress

	// BCC contains the list of blind carbon copy recipients (optional)
	BCC []EmailAddress

	// Subject is the email subject line (required)
	Subject string

	// ReplyTo specifies the email address for replies (optional)
	// If not set, replies will go to the From address
	ReplyTo *EmailAddress

	// Content contains the email body and formatting options (required)
	Content MailContent
}

MailOptions contains all the required and optional parameters for sending an email. This structure provides a comprehensive way to specify email details including recipients, content, and various email headers.

type RemoveEmailFromGroupResponse

type RemoveEmailFromGroupResponse struct {
	// Success indicates whether the operation completed successfully
	Success bool
	// Message provides additional details about the operation result
	Message string
	// AffectedRows indicates how many email addresses were successfully removed
	AffectedRows int64
}

RemoveEmailFromGroupResponse represents the result of removing an email from a group. It provides detailed information about the removal operation's success and impact.

type SendEmailResponse

type SendEmailResponse struct {
	// MessageList contains message IDs or status information for sent emails
	MessageList []string

	// EmailsLeft indicates the remaining email quota for the account
	EmailsLeft int64
}

SendEmailResponse contains the result of an email sending operation. It provides information about the sent messages and remaining quota.

Directories

Path Synopsis
internal
proto
Package proto contains generated protocol buffer files for internal use.
Package proto contains generated protocol buffer files for internal use.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL