nylas

package module
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Dec 28, 2025 License: MIT Imports: 41 Imported by: 0

README

nylas-go

Go Reference Go Report Card

Go SDK for Nylas API v3

Install

go get github.com/mqasimca/nylas-go

Requires Go 1.21+

Quick Start

package main

import (
    "context"
    "log"

    nylas "github.com/mqasimca/nylas-go"
)

func main() {
    client, err := nylas.NewClient(
        nylas.WithAPIKey("nyk_v0_..."),
    )
    if err != nil {
        log.Fatal(err)
    }

    ctx := context.Background()
    msgs, err := client.Messages.List(ctx, "grant-id", nil)
    if err != nil {
        log.Fatal(err)
    }

    for _, msg := range msgs.Data {
        log.Printf("%s: %s", msg.ID, msg.Subject)
    }
}

Available Services

Service Description
Messages Email messages (list, get, send, update, delete, scheduled messages)
Threads Email threads/conversations
Drafts Email drafts (create, update, send, delete)
Calendars Calendar management (CRUD, availability, free/busy, room resources)
Events Calendar events (CRUD, recurring events, RSVP)
Contacts Contact management (CRUD, contact groups)
Folders Email folders/labels
Attachments File attachments (get, download)
Grants OAuth grants management
Webhooks Webhook subscriptions (CRUD, rotate secret)
Auth OAuth2 authentication (URL generation, token exchange, refresh, revoke)
Scheduler Scheduling configurations and bookings
Notetakers AI meeting bot (record, transcribe, summarize)
Applications Application configuration and settings
RedirectURIs Redirect URI management
Connectors Email/calendar provider connectors
Credentials Provider credentials management
SmartCompose AI-powered message composition
Neural ML-powered email intelligence (categorization, OCR, signatures, cleaning)
VirtualCalendars Provider-agnostic virtual calendars

Configuration

// US region (default)
client, _ := nylas.NewClient(nylas.WithAPIKey("nyk_v0_..."))

// EU region
client, _ := nylas.NewClient(
    nylas.WithAPIKey("nyk_v0_..."),
    nylas.WithRegion(nylas.RegionEU),
)

// Custom HTTP client
client, _ := nylas.NewClient(
    nylas.WithAPIKey("nyk_v0_..."),
    nylas.WithHTTPClient(&http.Client{Timeout: 60 * time.Second}),
)

// Custom retry settings
client, _ := nylas.NewClient(
    nylas.WithAPIKey("nyk_v0_..."),
    nylas.WithMaxRetries(5),
    nylas.WithRetryWait(2 * time.Second),
)
Configuration Options
Option Description Default
WithAPIKey(key) API key (required) -
WithRegion(region) API region (RegionUS or RegionEU) RegionUS
WithBaseURL(url) Custom base URL https://api.us.nylas.com
WithHTTPClient(client) Custom HTTP client Default with 90s timeout
WithTimeout(duration) Request timeout 90 seconds
WithMaxRetries(n) Max retry attempts for 5xx/429 errors 2
WithRetryWait(duration) Base wait time between retries 500ms

Concurrency

The SDK is safe for concurrent use by multiple goroutines:

// Safe: Single client, multiple goroutines
client, _ := nylas.NewClient(nylas.WithAPIKey("nyk_v0_..."))

var wg sync.WaitGroup
for i := 0; i < 10; i++ {
    wg.Add(1)
    go func(id string) {
        defer wg.Done()
        msg, _ := client.Messages.Get(ctx, grantID, id)
        // Process msg
    }(fmt.Sprintf("msg-%d", i))
}
wg.Wait()

Thread Safety Guarantees:

  • ✅ Client is safe for concurrent use
  • ✅ HTTP connection pooling and reuse
  • ✅ Rate limit tracking is thread-safe
  • ❌ Iterators are NOT thread-safe (create separate iterators per goroutine)
// SAFE: Concurrent API calls with shared client
go func() { client.Messages.List(ctx, grantID, nil) }()
go func() { client.Calendars.List(ctx, grantID, nil) }()
go func() { client.Events.List(ctx, grantID, nil) }()

// UNSAFE: Sharing iterator across goroutines
iter := client.Messages.ListAll(ctx, grantID, nil)
go func() { iter.Next() }() // ❌ Race condition
go func() { iter.Next() }() // ❌ Race condition

// SAFE: Separate iterators per goroutine
go func() {
    iter := client.Messages.ListAll(ctx, grantID, nil)
    for {
        msg, err := iter.Next()
        if errors.Is(err, nylas.ErrDone) {
            break
        }
        process(msg)
    }
}()

Rate Limiting & Retries

The SDK automatically handles rate limiting and transient errors:

  • 429 Too Many Requests: Retries with Retry-After header value (or exponential backoff)
  • 5xx Server Errors: Retries with exponential backoff
  • Exponential Backoff: Wait time doubles with each retry attempt
// Check current rate limits after any API call
rate := client.RateLimits()
log.Printf("Limit: %d, Remaining: %d, Reset: %v",
    rate.Limit, rate.Remaining, rate.Reset)

Pagination

// Iterator pattern
iter := client.Messages.ListAll(ctx, grantID, nil)
for {
    msg, err := iter.Next()
    if errors.Is(err, nylas.ErrDone) {
        break
    }
    if err != nil {
        log.Fatal(err)
    }
    process(msg)
}

// Or collect all
all, err := iter.Collect()

Neural API (AI-Powered Email Intelligence)

Requires Nylas Plus plan

The Neural API provides ML-powered email intelligence features.

Message Categorization

Classify emails as "conversation" (important) or "feed" (newsletters, notifications):

import "github.com/mqasimca/nylas-go/neural"

// Categorize a single message
result, err := client.Neural.Categorize(ctx, grantID, messageID)
if err != nil {
    log.Fatal(err)
}
log.Printf("Category: %s (confidence: %.2f)",
    result.Categorizer.Category, result.Categorizer.Confidence)

// Batch categorize multiple messages
messageIDs := []string{"msg1", "msg2", "msg3"}
results, err := client.Neural.CategorizeBatch(ctx, grantID, messageIDs)
Clean Conversations

Remove signatures, reply chains, and clutter from emails:

result, err := client.Neural.CleanConversation(ctx, grantID, messageID,
    &neural.CleanConversationRequest{
        IgnoreLinks:      nylas.Ptr(true),
        RemoveConclusion: nylas.Ptr(true),
    })
log.Printf("Clean text: %s", result.Conversation)
Signature Extraction

Extract signatures and contact information from emails:

result, err := client.Neural.ExtractSignature(ctx, grantID, messageID,
    &neural.SignatureExtractionRequest{
        ParseContacts: nylas.Ptr(true),
    })
log.Printf("Signature: %s", result.Signature)
for _, contact := range result.Contacts {
    log.Printf("Name: %s, Email: %s, Title: %s",
        contact.Name, contact.Email, contact.JobTitle)
}
OCR / Text Extraction

Extract text from images in emails:

result, err := client.Neural.ExtractText(ctx, grantID, messageID, nil)
log.Printf("Extracted text: %s", result.OCR)
for _, imageURL := range result.Images {
    log.Printf("Image: %s", imageURL)
}

Virtual Calendars

Virtual calendars are provider-agnostic calendars that can aggregate availability across multiple providers.

import (
    "github.com/mqasimca/nylas-go/virtualcalendars"
)

// Create a virtual calendar
vc, err := client.VirtualCalendars.Create(ctx, grantID,
    &virtualcalendars.CreateRequest{
        Name:        "Aggregated Availability",
        Description: nylas.Ptr("Combined calendar across all providers"),
        Timezone:    nylas.Ptr("America/New_York"),
        Metadata: map[string]string{
            "team": "engineering",
        },
    })

// List virtual calendars
calendars, err := client.VirtualCalendars.List(ctx, grantID, nil)

// Get a specific virtual calendar
calendar, err := client.VirtualCalendars.Get(ctx, grantID, calendarID)

// Update virtual calendar
updated, err := client.VirtualCalendars.Update(ctx, grantID, calendarID,
    &virtualcalendars.UpdateRequest{
        Name: nylas.Ptr("Updated Name"),
    })

// Delete virtual calendar
err = client.VirtualCalendars.Delete(ctx, grantID, calendarID)

Room Resources (Google Workspace & Microsoft 365)

List and filter conference rooms and equipment:

import "github.com/mqasimca/nylas-go/calendars"

// List all room resources
resources, err := client.Calendars.ListResources(ctx, grantID, nil)
for _, resource := range resources.Data {
    log.Printf("Room: %s (%s) - Capacity: %d",
        resource.Name, resource.Email, resource.Capacity)
}

// Filter by email
resources, err = client.Calendars.ListResources(ctx, grantID,
    &calendars.ListResourcesOptions{
        Email: nylas.Ptr("conference-room-a@company.com"),
    })

// Paginate through resources
iter := client.Calendars.ListAllResources(ctx, grantID, nil)
for {
    resource, err := iter.Next()
    if errors.Is(err, nylas.ErrDone) {
        break
    }
    process(resource)
}

Batch Operations

Execute multiple operations concurrently:

// Batch get messages
messageIDs := []string{"msg1", "msg2", "msg3"}
results := nylas.BatchGet(ctx, grantID, messageIDs,
    client.Messages.Get)

for i, result := range results {
    if result.Err != nil {
        log.Printf("Message %d error: %v", i, result.Err)
    } else {
        log.Printf("Message %d: %s", i, result.Data.Subject)
    }
}

// Batch update with custom operations
type UpdateOp struct {
    ID      string
    Unread  bool
    Starred bool
}

updates := []UpdateOp{
    {ID: "msg1", Unread: false},
    {ID: "msg2", Starred: true},
}

results := nylas.BatchUpdate(ctx, grantID, updates,
    func(ctx context.Context, grantID string, op UpdateOp) (*messages.Message, error) {
        return client.Messages.Update(ctx, grantID, op.ID,
            &messages.UpdateRequest{
                Unread:  &op.Unread,
                Starred: &op.Starred,
            })
    })

// Batch delete (returns map of errors)
messageIDs := []string{"msg1", "msg2", "msg3"}
errors := nylas.BatchDelete(ctx, grantID, messageIDs,
    client.Messages.Delete)

for idx, err := range errors {
    log.Printf("Message %d deletion failed: %v", idx, err)
}

// Advanced batch control
op := &nylas.BatchOperation[string]{
    MaxConcurrency: 5,        // Limit concurrent operations
    StopOnError:    false,    // Continue on errors
}

errors := op.Execute(ctx, items, func(ctx context.Context, item string) error {
    return processItem(item)
})

Query Builder

Build complex queries with a fluent API:

// Build a message query
query := nylas.NewQueryBuilder().
    Subject("invoice").
    From("billing@company.com").
    Unread(true).
    Limit(50).
    Build()

messages, err := client.Messages.List(ctx, grantID,
    &messages.ListOptions{QueryParams: query})

// Event queries with time ranges
query := nylas.NewQueryBuilder().
    CalendarID("cal-123").
    StartTime(time.Now()).
    EndTime(time.Now().AddDate(0, 0, 7)).
    Build()

// Filter by metadata
query := nylas.NewQueryBuilder().
    Metadata("priority", "high").
    Metadata("team", "engineering").
    Build()

// Clone and modify queries
baseQuery := nylas.NewQueryBuilder().
    Limit(100).
    In("folder_id", []string{"inbox", "archive"})

unreadQuery := baseQuery.Clone().Unread(true).Build()
starredQuery := baseQuery.Clone().Starred(true).Build()

Context Helpers

Add request tracking and debugging:

// Add custom request ID for tracing
ctx := nylas.WithRequestID(context.Background(), "trace-12345")

msg, err := client.Messages.Get(ctx, grantID, messageID)

// Retrieve request ID from context
if requestID, ok := nylas.RequestIDFromContext(ctx); ok {
    log.Printf("Request ID: %s", requestID)
}

// Enable debug mode
ctx = nylas.WithDebug(context.Background(), true)

// Set custom user agent
ctx = nylas.WithUserAgent(ctx, "MyApp/1.0")

// Set idempotency key for safe retries
ctx = nylas.WithIdempotencyKey(ctx, "unique-operation-id")

// Combine multiple options
ctx = nylas.WithOptions(context.Background(), nylas.ContextOptions{
    RequestID:      "trace-12345",
    Debug:          true,
    UserAgent:      "MyApp/1.0",
    IdempotencyKey: "op-67890",
})

Logger

Pluggable logging interface for request/response debugging:

// Use standard logger
logger := nylas.NewStdLogger(nylas.LogLevelDebug)
// Configure client to use logger (future feature)

// Use structured logger with custom output
logger := nylas.NewStructuredLogger(nylas.LogLevelInfo,
    func(entry map[string]any) {
        json, _ := json.Marshal(entry)
        fmt.Println(string(json))
    })

logger.Info(ctx, "Processing messages",
    "count", 10,
    "grant_id", grantID)

// Noop logger for silent operation
logger := nylas.NewNoopLogger()

Error Handling

msg, err := client.Messages.Get(ctx, grantID, msgID)
if errors.Is(err, nylas.ErrNotFound) {
    // Handle not found
}
if errors.Is(err, nylas.ErrRateLimited) {
    // Handle rate limit (though SDK auto-retries)
}

var apiErr *nylas.APIError
if errors.As(err, &apiErr) {
    log.Printf("Status: %d, Request ID: %s", apiErr.StatusCode, apiErr.RequestID)
}
Sentinel Errors
Error Description
ErrMissingAPIKey API key not provided
ErrBadRequest 400 Bad Request
ErrUnauthorized 401 Unauthorized
ErrForbidden 403 Forbidden
ErrNotFound 404 Not Found
ErrConflict 409 Conflict
ErrValidation 422 Unprocessable Entity
ErrRateLimited 429 Too Many Requests
ErrServerError 5xx Server Error
ErrDone Iterator exhausted (pagination)
Enhanced Error Types

The SDK provides detailed error types for common scenarios:

// Validation errors (422)
var valErr *nylas.ValidationError
if errors.As(err, &valErr) {
    log.Printf("Validation failed on field '%s': %s (constraint: %s)",
        valErr.Field, valErr.Message, valErr.Constraint)
}

// Conflict errors (409)
var conflictErr *nylas.ConflictError
if errors.As(err, &conflictErr) {
    log.Printf("Conflict with %s: %s (type: %s)",
        conflictErr.ConflictingResource,
        conflictErr.Message,
        conflictErr.ConflictType)
}

// Quota exceeded errors
var quotaErr *nylas.QuotaExceededError
if errors.As(err, &quotaErr) {
    log.Printf("Quota exceeded: %s quota (usage: %d/%d, resets: %v)",
        quotaErr.QuotaType,
        quotaErr.Usage,
        quotaErr.Limit,
        quotaErr.ResetTime)
}

// Rate limit errors (429) with retry information
var rateLimitErr *nylas.RateLimitError
if errors.As(err, &rateLimitErr) {
    log.Printf("Rate limited: %d/%d requests remaining",
        rateLimitErr.Rate.Remaining,
        rateLimitErr.Rate.Limit)
}

Development

Install CI Tools
make install-tools

This installs pinned versions of:

  • golangci-lint - Linter
  • govulncheck - Vulnerability scanner
  • gosec - Security scanner
Makefile Commands
Command Description
make ci Run all CI checks (required before code changes)
make ci-full Run CI + integration tests (output saved to ci-full.txt)
make test Run unit tests
make test-race Run tests with race detector
make test-integration Run integration tests
make test-suite SUITE=X Run specific test suite (Messages, Threads, Drafts)
make test-coverage Run tests with coverage report
make lint Run golangci-lint
make security Run gosec security scan
make vuln Run govulncheck
make fmt Format code
make help Show all available commands
CI Checks

make ci runs 9 checks:

  1. go mod verify - Verify dependencies
  2. go mod tidy - Check go.mod/go.sum
  3. gofmt - Check formatting
  4. go vet - Static analysis
  5. golangci-lint - Linting
  6. gosec - Security scan
  7. govulncheck - Vulnerability scan
  8. go build - Build verification
  9. go test -race - Tests with race detector

Testing

Unit Tests
make test          # Run unit tests
make test-race     # Run with race detector
make test-unit-v   # Run with verbose output
Integration Tests

Integration tests run against the live Nylas API with multiple provider support.

Required Environment Variables:

export NYLAS_API_KEY="nyk_v0_..."

# Provider grant IDs (at least one required)
export NYLAS_GOOGLE_GRANT_ID="..."
export NYLAS_MICROSOFT_GRANT_ID="..."
export NYLAS_ICLOUD_GRANT_ID="..."
export NYLAS_YAHOO_GRANT_ID="..."
export NYLAS_IMAP_GRANT_ID="..."
export NYLAS_EWS_GRANT_ID="..."

Run integration tests:

make test-integration              # All integration tests
make test-suite SUITE=Messages     # Messages tests only
make test-suite SUITE=Threads      # Threads tests only
make test-suite SUITE=Drafts       # Drafts tests only
make ci-full                       # Full CI + integration (saves to ci-full.txt)

Integration tests automatically loop through all configured providers, running each test against Google, Microsoft, iCloud, etc.

Documentation

License

MIT

Documentation

Overview

Package nylas provides a Go client for the Nylas API v3.

The client supports all major Nylas API resources including Messages, Threads, Drafts, Calendars, Events, Contacts, Folders, Attachments, Grants, and Webhooks.

Creating a Client

Create a client with your API key:

client, err := nylas.NewClient(
    nylas.WithAPIKey("your-api-key"),
)

For EU region:

client, err := nylas.NewClient(
    nylas.WithAPIKey("your-api-key"),
    nylas.WithRegion(nylas.RegionEU),
)

Using Services

Access Nylas resources through service methods:

// List messages
resp, err := client.Messages.List(ctx, grantID, nil)

// Get a single message
msg, err := client.Messages.Get(ctx, grantID, messageID)

// Send a message
msg, err := client.Messages.Send(ctx, grantID, &messages.SendRequest{
    To:      []messages.Participant{{Email: "recipient@example.com"}},
    Subject: "Hello",
    Body:    "World",
})

Pagination

Use iterators for paginated results:

iter := client.Messages.ListAll(ctx, grantID, nil)
for {
    msg, err := iter.Next()
    if errors.Is(err, nylas.ErrDone) {
        break
    }
    if err != nil {
        return err
    }
    process(msg)
}

Or collect all results at once:

all, err := iter.Collect()

Error Handling

Check for specific error conditions:

if errors.Is(err, nylas.ErrNotFound) {
    // Resource not found
}
if errors.Is(err, nylas.ErrRateLimited) {
    // Rate limited, retry later
}

Rate Limiting

The client automatically handles rate limiting with exponential backoff. You can also check current rate limit status:

limits := client.RateLimits()
fmt.Printf("Remaining: %d, Reset: %v\n", limits.Remaining, limits.Reset)
Example (AdvancedRetry)
package main

import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/mqasimca/nylas-go"
)

func main() {
	// Configure advanced retry behavior
	client, _ := nylas.NewClient(
		nylas.WithAPIKey("your-api-key"),
		nylas.WithMaxRetries(3),
		nylas.WithRetryWait(500*time.Millisecond), // 500ms base wait
		nylas.WithMaxRetryWait(30*time.Second),    // 30s max wait
	)

	ctx := context.Background()
	_, err := client.Messages.List(ctx, "grant-id", nil)
	if err != nil {
		// Check if rate limited after all retries
		var rateLimitErr *nylas.RateLimitError
		if errors.As(err, &rateLimitErr) {
			log.Printf("Rate limited until: %v", rateLimitErr.Rate.Reset)
			log.Printf("Limit: %d, Remaining: %d", rateLimitErr.Rate.Limit, rateLimitErr.Rate.Remaining)
		}
	}
}
Example (CompleteWorkflow)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/mqasimca/nylas-go"
	"github.com/mqasimca/nylas-go/events"
	"github.com/mqasimca/nylas-go/messages"
)

func main() {
	// Complete example: Search messages, send reply, create calendar event
	client, _ := nylas.NewClient(
		nylas.WithAPIKey("your-api-key"),
		nylas.WithMaxRetries(3),
	)
	ctx := context.Background()
	grantID := "your-grant-id"

	// 1. Search for unread messages from specific sender
	msgs, err := client.Messages.List(ctx, grantID, &messages.ListOptions{
		From:   nylas.Ptr("boss@company.com"),
		Unread: nylas.Ptr(true),
		Limit:  nylas.Ptr(10),
	})
	if err != nil {
		log.Fatal(err)
	}

	if len(msgs.Data) == 0 {
		fmt.Println("No unread messages")
		return
	}

	// 2. Send reply to first message
	firstMsg := msgs.Data[0]
	reply, err := client.Messages.Send(ctx, grantID, &messages.SendRequest{
		To:               firstMsg.From,
		Subject:          "Re: " + firstMsg.Subject,
		Body:             "I'll look into this right away.",
		ReplyToMessageID: firstMsg.ID,
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Sent reply: %s\n", reply.ID)

	// 3. Mark original as read
	_, err = client.Messages.Update(ctx, grantID, firstMsg.ID, &messages.UpdateRequest{
		Unread: nylas.Ptr(false),
	})
	if err != nil {
		log.Fatal(err)
	}

	// 4. Create follow-up calendar event
	event, err := client.Events.Create(ctx, grantID, "primary", &events.CreateRequest{
		Title:       "Follow up on: " + firstMsg.Subject,
		Description: "Review and respond to request",
		When: events.When{
			StartTime: nylas.Ptr(int64(1704067200)),
			EndTime:   nylas.Ptr(int64(1704070800)),
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Created follow-up event: %s\n", event.ID)
}
Example (ConcurrentRequests)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/mqasimca/nylas-go"
)

func main() {
	client, _ := nylas.NewClient(nylas.WithAPIKey("your-api-key"))
	ctx := context.Background()
	grantID := "your-grant-id"

	// Client is safe for concurrent use
	type result struct {
		name string
		err  error
	}

	results := make(chan result, 3)

	// Fetch messages, calendars, and events concurrently
	go func() {
		_, err := client.Messages.List(ctx, grantID, nil)
		results <- result{"messages", err}
	}()

	go func() {
		_, err := client.Calendars.List(ctx, grantID, nil)
		results <- result{"calendars", err}
	}()

	go func() {
		_, err := client.Events.List(ctx, grantID, nil)
		results <- result{"events", err}
	}()

	// Collect results
	for i := 0; i < 3; i++ {
		res := <-results
		if res.err != nil {
			log.Printf("Error fetching %s: %v", res.name, res.err)
		} else {
			fmt.Printf("Successfully fetched %s\n", res.name)
		}
	}
}
Example (ErrorHandling)
package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/mqasimca/nylas-go"
)

func main() {
	client, _ := nylas.NewClient(nylas.WithAPIKey("your-api-key"))
	ctx := context.Background()

	_, err := client.Messages.Get(ctx, "grant-id", "invalid-message-id")
	if err != nil {
		// Check for specific error types
		if errors.Is(err, nylas.ErrNotFound) {
			fmt.Println("Message not found")
			return
		}
		if errors.Is(err, nylas.ErrUnauthorized) {
			fmt.Println("Invalid API key")
			return
		}
		if errors.Is(err, nylas.ErrRateLimited) {
			fmt.Println("Rate limited - try again later")
			return
		}

		// Get detailed error information
		var apiErr *nylas.APIError
		if errors.As(err, &apiErr) {
			fmt.Printf("API Error: %s (status: %d, request_id: %s)\n",
				apiErr.Message, apiErr.StatusCode, apiErr.RequestID)
		}
	}
}
Example (Pagination)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/mqasimca/nylas-go"
	"github.com/mqasimca/nylas-go/messages"
)

func main() {
	client, _ := nylas.NewClient(nylas.WithAPIKey("your-api-key"))
	ctx := context.Background()
	grantID := "your-grant-id"

	// Manual pagination with NextCursor
	var allMessages []messages.Message
	var cursor string

	for {
		resp, err := client.Messages.List(ctx, grantID, &messages.ListOptions{
			Limit:     nylas.Ptr(50),
			PageToken: cursor,
		})
		if err != nil {
			log.Fatal(err)
		}

		allMessages = append(allMessages, resp.Data...)

		if resp.NextCursor == "" {
			break // No more pages
		}
		cursor = resp.NextCursor
	}

	fmt.Printf("Fetched %d messages across multiple pages\n", len(allMessages))
}
Example (RateLimitMonitoring)
package main

import (
	"context"
	"log"

	"github.com/mqasimca/nylas-go"
)

func main() {
	client, _ := nylas.NewClient(
		nylas.WithAPIKey("your-api-key"),
		nylas.WithRateLimitWarningThreshold(0.2), // Warn at 20% remaining
	)

	// Register observer to monitor rate limits
	client.OnRateLimit(func(rate nylas.Rate) {
		if rate.IsNearLimit(0.1) { // Less than 10% remaining
			log.Printf("WARNING: Only %d/%d requests remaining", rate.Remaining, rate.Limit)
		}
	})

	// All API calls will now trigger rate limit monitoring
	ctx := context.Background()
	_, _ = client.Messages.List(ctx, "grant-id", nil)
}
Example (RateLimits)
package main

import (
	"fmt"

	"github.com/mqasimca/nylas-go"
)

func main() {
	client, _ := nylas.NewClient(nylas.WithAPIKey("your-api-key"))

	// Check current rate limit status
	limits := client.RateLimits()
	fmt.Printf("Remaining: %d, Reset: %v\n", limits.Remaining, limits.Reset)
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrMissingAPIKey = errors.New("nylas: API key required (use WithAPIKey)")
	ErrUnauthorized  = errors.New("nylas: unauthorized")
	ErrNotFound      = errors.New("nylas: not found")
	ErrRateLimited   = errors.New("nylas: rate limited")
	ErrBadRequest    = errors.New("nylas: bad request")
	ErrServerError   = errors.New("nylas: server error")
)

Sentinel errors for common API error conditions. Use errors.Is to check for these conditions:

if errors.Is(err, nylas.ErrNotFound) {
    // handle not found
}
View Source
var (
	// Additional sentinel errors
	ErrConflict   = errors.New("nylas: resource conflict")
	ErrValidation = errors.New("nylas: validation error")
)
View Source
var ErrDone = errors.New("no more items")

ErrDone is returned by Iterator.Next when iteration is complete.

Functions

func BatchDelete added in v0.1.4

func BatchDelete(
	ctx context.Context,
	grantID string,
	ids []string,
	deleteFn func(context.Context, string, string) error,
) map[int]error

BatchDelete executes multiple Delete operations concurrently and returns errors. Returns a map of index to error for failed deletions.

Example:

errors := nylas.BatchDelete(ctx, grantID, messageIDs, client.Messages.Delete)
for index, err := range errors {
    log.Printf("Failed to delete message %d: %v", index, err)
}

func ExtractChallengeParameter added in v0.1.3

func ExtractChallengeParameter(webhookURL string) (string, error)

ExtractChallengeParameter extracts the challenge parameter from a webhook validation URL. When Nylas validates a webhook endpoint, it sends a GET request with a challenge query parameter. Your endpoint must return this challenge value in the response body within 10 seconds.

Example URL: https://your-webhook.com/endpoint?challenge=abc123 Returns: "abc123", nil

func IdempotencyKeyFromContext added in v0.1.4

func IdempotencyKeyFromContext(ctx context.Context) (string, bool)

IdempotencyKeyFromContext retrieves the idempotency key from the context.

func IsDebug added in v0.1.4

func IsDebug(ctx context.Context) bool

IsDebug returns true if debug mode is enabled in the context.

func Ptr

func Ptr[T any](v T) *T

Ptr returns a pointer to v.

func RequestIDFromContext added in v0.1.4

func RequestIDFromContext(ctx context.Context) (string, bool)

RequestIDFromContext retrieves the request ID from the context.

func UserAgentFromContext added in v0.1.4

func UserAgentFromContext(ctx context.Context) (string, bool)

UserAgentFromContext retrieves the custom user agent from the context.

func WithDebug added in v0.1.4

func WithDebug(ctx context.Context) context.Context

WithDebug enables debug mode for requests made with this context. In debug mode, the SDK may log additional information about requests and responses.

Example:

ctx := nylas.WithDebug(context.Background())
msg, err := client.Messages.Send(ctx, grantID, sendReq)

func WithIdempotencyKey added in v0.1.4

func WithIdempotencyKey(ctx context.Context, key string) context.Context

WithIdempotencyKey adds an idempotency key to the context. The idempotency key is sent as a header to prevent duplicate operations.

Example:

ctx := nylas.WithIdempotencyKey(context.Background(), "unique-operation-123")
msg, err := client.Messages.Send(ctx, grantID, sendReq)

func WithOptions added in v0.1.4

func WithOptions(parent context.Context, opts ContextOptions) context.Context

WithOptions creates a new context with all specified options.

Example:

ctx := nylas.WithOptions(context.Background(), nylas.ContextOptions{
    RequestID:      "trace-123",
    Debug:          true,
    Timeout:        30 * time.Second,
    IdempotencyKey: "operation-456",
})
msg, err := client.Messages.Send(ctx, grantID, sendReq)

func WithRequestID added in v0.1.4

func WithRequestID(ctx context.Context, requestID string) context.Context

WithRequestID adds a custom request ID to the context. This can be used for distributed tracing and log correlation.

Example:

ctx := nylas.WithRequestID(context.Background(), "trace-123")
msg, err := client.Messages.Get(ctx, grantID, messageID)

func WithUserAgent added in v0.1.4

func WithUserAgent(ctx context.Context, userAgent string) context.Context

WithUserAgent adds a custom user agent to the context. This overrides the default SDK user agent for requests made with this context.

Example:

ctx := nylas.WithUserAgent(context.Background(), "MyApp/1.0")
msg, err := client.Messages.List(ctx, grantID, nil)

Types

type APIError

type APIError struct {
	StatusCode int    `json:"-"`
	Type       string `json:"type"`
	Message    string `json:"message"`
	RequestID  string `json:"request_id"`
}

APIError represents an error response from the Nylas API.

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface.

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is implements errors.Is for matching against sentinel errors.

type ApplicationsService added in v0.1.3

type ApplicationsService service

ApplicationsService handles application configuration operations.

func (*ApplicationsService) GetDetails added in v0.1.3

GetDetails returns the application configuration details.

type AttachmentsService

type AttachmentsService service

AttachmentsService handles operations on email attachments.

func (*AttachmentsService) Download added in v0.1.2

func (s *AttachmentsService) Download(ctx context.Context, grantID, attachmentID, messageID string) (*attachments.DownloadResponse, error)

Download downloads an attachment and returns the response.

func (*AttachmentsService) Get added in v0.1.2

func (s *AttachmentsService) Get(ctx context.Context, grantID, attachmentID, messageID string) (*attachments.Attachment, error)

Get returns attachment metadata.

type AuthService

type AuthService service

AuthService handles authentication operations.

func (*AuthService) AccessTokenInfo added in v0.1.3

func (s *AuthService) AccessTokenInfo(ctx context.Context, accessToken string) (*auth.TokenInfoResponse, error)

AccessTokenInfo retrieves information about an access token.

func (*AuthService) CustomAuthentication added in v0.1.3

func (s *AuthService) CustomAuthentication(ctx context.Context, req *auth.CustomAuthRequest) (*grants.Grant, error)

CustomAuthentication performs custom/native authentication to create a grant. Use this for server-side authentication where you already have provider tokens.

func (*AuthService) DetectProvider added in v0.1.3

DetectProvider detects the email provider for an email address.

func (*AuthService) ExchangeCodeForToken added in v0.1.3

func (s *AuthService) ExchangeCodeForToken(ctx context.Context, req *auth.CodeExchangeRequest) (*auth.TokenExchangeResponse, error)

ExchangeCodeForToken exchanges an authorization code for access and refresh tokens. This is the final step of the OAuth 2.0 authorization code flow.

Example:

// After user is redirected back with ?code=xxx
tokens, err := client.Auth.ExchangeCodeForToken(ctx, &auth.CodeExchangeRequest{
    ClientID:    "your-client-id",
    RedirectURI: "https://yourapp.com/callback",
    Code:        code, // From query parameter
})
if err != nil {
    return err
}

// Store tokens.GrantID to access user's data
// tokens.AccessToken expires in 1 hour
// tokens.RefreshToken can be used to get new access tokens

func (*AuthService) IDTokenInfo added in v0.1.3

func (s *AuthService) IDTokenInfo(ctx context.Context, idToken string) (*auth.TokenInfoResponse, error)

IDTokenInfo validates an ID token and returns information about it.

func (*AuthService) RefreshAccessToken added in v0.1.3

func (s *AuthService) RefreshAccessToken(ctx context.Context, req *auth.RefreshTokenRequest) (*auth.TokenExchangeResponse, error)

RefreshAccessToken refreshes an expired access token using a refresh token. Access tokens expire after one hour; use this method to get a new one.

Example:

tokens, err := client.Auth.RefreshAccessToken(ctx, &auth.RefreshTokenRequest{
    ClientID:     "your-client-id",
    RefreshToken: storedRefreshToken,
})
if err != nil {
    // Handle error - user may need to re-authenticate
    return err
}
// Update stored tokens with new values

func (*AuthService) Revoke added in v0.1.3

func (s *AuthService) Revoke(ctx context.Context, token string) error

Revoke revokes an access token or refresh token. Returns true if the token was successfully revoked.

func (*AuthService) URLForAdminConsent added in v0.1.3

func (s *AuthService) URLForAdminConsent(config *auth.AdminConsentURLConfig) string

URLForAdminConsent generates an OAuth 2.0 admin consent URL for Microsoft. This is used for Microsoft 365 tenant-wide admin consent.

func (*AuthService) URLForOAuth2 added in v0.1.3

func (s *AuthService) URLForOAuth2(config *auth.URLForAuthenticationConfig) string

URLForOAuth2 generates an OAuth 2.0 authorization URL. Users should be redirected to this URL to authenticate with their email provider.

Example - basic OAuth flow:

authURL := client.Auth.URLForOAuth2(&auth.URLForAuthenticationConfig{
    ClientID:    "your-client-id",
    RedirectURI: "https://yourapp.com/callback",
})
// Redirect user to authURL

Example - with provider hint and scopes:

authURL := client.Auth.URLForOAuth2(&auth.URLForAuthenticationConfig{
    ClientID:    "your-client-id",
    RedirectURI: "https://yourapp.com/callback",
    Provider:    "google",
    LoginHint:   "user@gmail.com",
    Scopes:      []string{"email", "calendar"},
    State:       "random-state-for-csrf-protection",
    AccessType:  "offline", // Required for refresh tokens
})

func (*AuthService) URLForOAuth2PKCE added in v0.1.3

func (s *AuthService) URLForOAuth2PKCE(config *auth.PKCEURLConfig) string

URLForOAuth2PKCE generates an OAuth 2.0 authorization URL with PKCE support. Use this for public clients (mobile apps, SPAs) where the client secret cannot be securely stored.

Example:

// Generate a code verifier and challenge (use crypto/rand in production)
codeVerifier := "random-43-to-128-character-string"
h := sha256.Sum256([]byte(codeVerifier))
codeChallenge := base64.RawURLEncoding.EncodeToString(h[:])

authURL := client.Auth.URLForOAuth2PKCE(&auth.PKCEURLConfig{
    ClientID:            "your-client-id",
    RedirectURI:         "https://yourapp.com/callback",
    CodeChallenge:       codeChallenge,
    CodeChallengeMethod: "S256",
    State:               "random-state",
})
// Redirect user to authURL, then exchange code with codeVerifier

func (*AuthService) ValidateAccessToken added in v0.1.3

func (s *AuthService) ValidateAccessToken(ctx context.Context, accessToken string) (*auth.TokenInfoResponse, error)

ValidateAccessToken validates an access token and returns information about it. Deprecated: Use AccessTokenInfo instead.

type BatchOperation added in v0.1.4

type BatchOperation[T any] struct {
	// MaxConcurrency limits the number of concurrent operations.
	// Default: unlimited (all operations run concurrently).
	MaxConcurrency int
	// StopOnError stops executing remaining operations if any operation fails.
	// Default: false (all operations execute regardless of failures).
	StopOnError bool
}

BatchOperation represents a generic batch operation configuration.

func (*BatchOperation[T]) Execute added in v0.1.4

func (b *BatchOperation[T]) Execute(
	ctx context.Context,
	items []T,
	fn func(context.Context, T) error,
) []error

Execute runs a batch operation with the given configuration.

type BatchResult added in v0.1.4

type BatchResult[T any] struct {
	Index int
	Data  *T
	Err   error
}

BatchResult represents the result of a batch operation.

func BatchCreate added in v0.1.4

func BatchCreate[T any, U any](
	ctx context.Context,
	grantID string,
	requests []U,
	createFn func(context.Context, string, U) (*T, error),
) []BatchResult[T]

BatchCreate executes multiple Create operations concurrently and returns results.

Example:

requests := []*messages.SendRequest{...}
results := nylas.BatchCreate(ctx, grantID, requests, client.Messages.Send)

func BatchGet added in v0.1.4

func BatchGet[T any](
	ctx context.Context,
	grantID string,
	ids []string,
	getFn func(context.Context, string, string) (*T, error),
) []BatchResult[T]

BatchGet executes multiple Get operations concurrently and returns results. The order of results matches the order of IDs provided.

Example:

results := nylas.BatchGet(ctx, grantID, messageIDs, client.Messages.Get)
for _, result := range results {
    if result.Err != nil {
        log.Printf("Error getting message %d: %v", result.Index, result.Err)
        continue
    }
    process(result.Data)
}

func BatchUpdate added in v0.1.4

func BatchUpdate[T any, U any](
	ctx context.Context,
	grantID string,
	updates []U,
	updateFn func(context.Context, string, U) (*T, error),
) []BatchResult[T]

BatchUpdate executes multiple Update operations concurrently and returns results. The order of results matches the order of updates provided.

Example:

type Update struct {
    ID      string
    Request *events.UpdateRequest
}
updates := []Update{...}
results := nylas.BatchUpdate(ctx, grantID, updates,
    func(ctx context.Context, grantID string, update Update) (*events.Event, error) {
        return client.Events.Update(ctx, grantID, update.ID, update.Request)
    })

type CalendarsService

type CalendarsService service

CalendarsService handles operations on calendars.

func (*CalendarsService) Availability added in v0.1.2

Availability checks availability for participants.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/mqasimca/nylas-go"
	"github.com/mqasimca/nylas-go/calendars"
)

func main() {
	client, _ := nylas.NewClient(nylas.WithAPIKey("your-api-key"))
	ctx := context.Background()

	// Check availability for multiple participants
	availability, err := client.Calendars.Availability(ctx, &calendars.AvailabilityRequest{
		StartTime:       1704067200,
		EndTime:         1704153600,
		DurationMinutes: 30,
		Participants: []calendars.AvailabilityParticipant{
			{Email: "user1@example.com"},
			{Email: "user2@example.com"},
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	for _, slot := range availability.TimeSlots {
		fmt.Printf("Available: %d - %d\n", slot.StartTime, slot.EndTime)
	}
}

func (*CalendarsService) Create added in v0.1.2

func (s *CalendarsService) Create(ctx context.Context, grantID string, create *calendars.CreateRequest) (*calendars.Calendar, error)

Create creates a new calendar.

func (*CalendarsService) Delete added in v0.1.2

func (s *CalendarsService) Delete(ctx context.Context, grantID, calendarID string) error

Delete deletes a calendar.

func (*CalendarsService) FreeBusy added in v0.1.2

FreeBusy returns free/busy information for emails.

func (*CalendarsService) Get added in v0.1.2

func (s *CalendarsService) Get(ctx context.Context, grantID, calendarID string) (*calendars.Calendar, error)

Get returns a single calendar.

func (*CalendarsService) List added in v0.1.2

List returns calendars for a grant.

func (*CalendarsService) ListAll added in v0.1.2

ListAll returns an iterator for all calendars.

func (*CalendarsService) ListAllResources added in v0.1.4

func (s *CalendarsService) ListAllResources(ctx context.Context, grantID string, opts *calendars.ListResourcesOptions) *Iterator[calendars.Resource]

ListAllResources returns an iterator for all room resources.

func (*CalendarsService) ListResources added in v0.1.4

ListResources returns room resources available for booking (conference rooms, equipment, etc.).

Note: Room resources availability depends on the calendar provider (Google Workspace, Microsoft 365).

func (*CalendarsService) Update added in v0.1.2

func (s *CalendarsService) Update(ctx context.Context, grantID, calendarID string, update *calendars.UpdateRequest) (*calendars.Calendar, error)

Update updates a calendar.

type CircuitBreakerConfig added in v0.1.4

type CircuitBreakerConfig struct {
	// MaxRequests is the maximum number of requests allowed to pass through
	// when the circuit breaker is half-open. Default: 1
	MaxRequests uint32

	// Interval is the cyclic period of the closed state for the circuit breaker
	// to clear the internal counts. If Interval is 0, the circuit breaker doesn't
	// clear internal counts during the closed state. Default: 0
	Interval time.Duration

	// Timeout is the period of the open state, after which the state becomes half-open.
	// Default: 60 seconds
	Timeout time.Duration

	// ReadyToTrip is called with a copy of Counts whenever a request fails in the closed state.
	// If ReadyToTrip returns true, the circuit breaker will be placed into the open state.
	// If ReadyToTrip is nil, default behavior is: trip after 5 consecutive failures.
	ReadyToTrip func(counts gobreaker.Counts) bool

	// OnStateChange is called whenever the state of the circuit breaker changes.
	OnStateChange func(name string, from gobreaker.State, to gobreaker.State)
}

CircuitBreakerConfig holds configuration for the circuit breaker.

func DefaultCircuitBreakerConfig added in v0.1.4

func DefaultCircuitBreakerConfig() CircuitBreakerConfig

DefaultCircuitBreakerConfig returns a circuit breaker config with sensible defaults.

type CircuitBreakerCounts added in v0.1.4

type CircuitBreakerCounts struct {
	Requests             uint32 // Total number of requests
	TotalSuccesses       uint32 // Total successful requests
	TotalFailures        uint32 // Total failed requests
	ConsecutiveSuccesses uint32 // Consecutive successful requests
	ConsecutiveFailures  uint32 // Consecutive failed requests
}

CircuitBreakerCounts holds statistics about the circuit breaker.

type CircuitBreakerState added in v0.1.4

type CircuitBreakerState string

CircuitBreakerState represents the state of the circuit breaker.

const (
	// CircuitBreakerStateClosed means requests are passing through normally
	CircuitBreakerStateClosed CircuitBreakerState = "closed"

	// CircuitBreakerStateHalfOpen means the circuit breaker is testing if the service recovered
	CircuitBreakerStateHalfOpen CircuitBreakerState = "half-open"

	// CircuitBreakerStateOpen means the circuit breaker is rejecting requests
	CircuitBreakerStateOpen CircuitBreakerState = "open"
)

func (CircuitBreakerState) String added in v0.1.4

func (s CircuitBreakerState) String() string

String returns the string representation of the circuit breaker state.

type Client

type Client struct {
	APIKey     string
	BaseURL    string
	HTTPClient *http.Client

	MaxRetries    int
	RetryWait     time.Duration
	MaxRetryWait  time.Duration
	DisableJitter bool

	Messages         *MessagesService
	Threads          *ThreadsService
	Drafts           *DraftsService
	Calendars        *CalendarsService
	Events           *EventsService
	Contacts         *ContactsService
	Folders          *FoldersService
	Attachments      *AttachmentsService
	Grants           *GrantsService
	Webhooks         *WebhooksService
	Auth             *AuthService
	Scheduler        *SchedulerService
	Notetakers       *NotetakersService
	Applications     *ApplicationsService
	RedirectURIs     *RedirectURIsService
	Connectors       *ConnectorsService
	Credentials      *CredentialsService
	SmartCompose     *SmartComposeService
	Neural           *NeuralService
	VirtualCalendars *VirtualCalendarsService
	// contains filtered or unexported fields
}

Client is the Nylas API client. It is safe for concurrent use by multiple goroutines.

func NewClient

func NewClient(opts ...Option) (*Client, error)

NewClient creates a new Nylas API client. An API key is required; use WithAPIKey to provide it.

Example:

client, err := nylas.NewClient(
    nylas.WithAPIKey("your-api-key"),
    nylas.WithRegion(nylas.RegionEU),
)
Example
package main

import (
	"log"

	"github.com/mqasimca/nylas-go"
)

func main() {
	// Create a client with your API key
	client, err := nylas.NewClient(
		nylas.WithAPIKey("your-api-key"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Use the client to access Nylas services
	_ = client.Messages
	_ = client.Calendars
	_ = client.Events
}
Example (WithOptions)
package main

import (
	"log"

	"github.com/mqasimca/nylas-go"
)

func main() {
	// Create a client with multiple options
	client, err := nylas.NewClient(
		nylas.WithAPIKey("your-api-key"),
		nylas.WithRegion(nylas.RegionEU), // Use EU region
		nylas.WithMaxRetries(3),          // Retry failed requests
	)
	if err != nil {
		log.Fatal(err)
	}

	_ = client
}

func (*Client) CircuitBreakerCounts added in v0.1.4

func (c *Client) CircuitBreakerCounts() CircuitBreakerCounts

CircuitBreakerCounts returns the current statistics of the circuit breaker. Returns zero counts if circuit breaker is not enabled.

func (*Client) CircuitBreakerState added in v0.1.4

func (c *Client) CircuitBreakerState() CircuitBreakerState

CircuitBreakerState returns the current state of the circuit breaker. Returns CircuitBreakerStateClosed if circuit breaker is not enabled.

func (*Client) Do

func (c *Client) Do(req *http.Request, v any) (*Response[any], error)

Do executes an HTTP request and decodes the JSON response into v. The response is expected to be wrapped in a standard Nylas response envelope with data and request_id fields.

func (*Client) DoList

func (c *Client) DoList(req *http.Request, v any) (string, string, error)

DoList executes a request and decodes a list response with pagination.

func (*Client) DoRaw

func (c *Client) DoRaw(req *http.Request, v any) error

DoRaw executes a request and decodes the response directly (not wrapped in data/request_id). Use this for endpoints that return arrays or objects directly without the standard wrapper.

func (*Client) NewMultipartRequest added in v0.1.4

func (c *Client) NewMultipartRequest(ctx context.Context, method, path string, fields map[string]string, files map[string][]byte) (*http.Request, error)

NewMultipartRequest creates a multipart form request for file uploads. Use this for sending messages/drafts with attachments larger than 3MB.

func (*Client) NewRequest

func (c *Client) NewRequest(ctx context.Context, method, path string, body any) (*http.Request, error)

NewRequest creates an HTTP request for the Nylas API with proper headers and authentication.

func (*Client) OnRateLimit added in v0.1.4

func (c *Client) OnRateLimit(observer RateLimitObserver)

OnRateLimit registers an observer callback that is called whenever rate limit information is updated from an API response. Observers are called outside the rate limit mutex lock to prevent deadlocks, so they can safely call other client methods.

Example:

client.OnRateLimit(func(rate nylas.Rate) {
    if rate.IsNearLimit(0.1) {  // Less than 10% remaining
        log.Printf("WARNING: Only %d/%d requests remaining", rate.Remaining, rate.Limit)
    }
})

func (*Client) RateLimits

func (c *Client) RateLimits() Rate

RateLimits returns the current rate limit information from the last API response.

func (*Client) SetRateLimitWarningThreshold added in v0.1.4

func (c *Client) SetRateLimitWarningThreshold(threshold float64)

SetRateLimitWarningThreshold sets the threshold for automatic rate limit warnings. When remaining requests drop below this percentage (0.0-1.0), the onRateLimitWarning callback is triggered. Set to 0 to disable warnings (default).

Example: threshold=0.2 triggers warning when < 20% of requests remain.

func (*Client) Use added in v0.1.4

func (c *Client) Use(middleware ...Middleware)

Use adds middleware to the client's HTTP transport chain. Middleware is executed in the order it was added (first added = outermost).

Example:

client.Use(LoggingMiddleware)
client.Use(MetricsMiddleware)
// Request flow: LoggingMiddleware -> MetricsMiddleware -> HTTP Request

func (*Client) WithLogger added in v0.1.4

func (c *Client) WithLogger(logger Logger) *Client

WithLogger sets a custom logger on the client.

Example using standard logger:

client.WithLogger(nylas.NewStdLogger(nylas.LogLevelInfo))

Example with no logging:

client.WithLogger(&nylas.NoopLogger{})

type ConflictError added in v0.1.4

type ConflictError struct {
	APIError
	ConflictingResource string `json:"conflicting_resource,omitempty"`
	ConflictType        string `json:"conflict_type,omitempty"`
}

ConflictError represents a resource conflict error (409).

func (*ConflictError) Error added in v0.1.4

func (e *ConflictError) Error() string

Error implements the error interface.

type ConnectorsService added in v0.1.3

type ConnectorsService service

ConnectorsService handles connector operations.

func (*ConnectorsService) Create added in v0.1.3

Create creates a new connector.

func (*ConnectorsService) Delete added in v0.1.3

func (s *ConnectorsService) Delete(ctx context.Context, provider connectors.Provider) error

Delete deletes a connector.

func (*ConnectorsService) Get added in v0.1.3

Get returns a single connector by provider.

func (*ConnectorsService) List added in v0.1.3

List returns all connectors.

func (*ConnectorsService) ListAll added in v0.1.3

ListAll returns an iterator for all connectors.

func (*ConnectorsService) Update added in v0.1.3

Update updates a connector.

type ContactsService

type ContactsService service

ContactsService handles operations on contacts.

func (*ContactsService) Create added in v0.1.2

func (s *ContactsService) Create(ctx context.Context, grantID string, create *contacts.CreateRequest) (*contacts.Contact, error)

Create creates a new contact.

func (*ContactsService) Delete added in v0.1.2

func (s *ContactsService) Delete(ctx context.Context, grantID, contactID string) error

Delete deletes a contact.

func (*ContactsService) Get added in v0.1.2

func (s *ContactsService) Get(ctx context.Context, grantID, contactID string) (*contacts.Contact, error)

Get returns a single contact.

func (*ContactsService) List added in v0.1.2

List returns contacts for a grant.

func (*ContactsService) ListAll added in v0.1.2

ListAll returns an iterator for all contacts.

func (*ContactsService) ListGroups added in v0.1.2

func (s *ContactsService) ListGroups(ctx context.Context, grantID string) ([]contacts.Group, error)

ListGroups returns contact groups for a grant.

func (*ContactsService) Update added in v0.1.2

func (s *ContactsService) Update(ctx context.Context, grantID, contactID string, update *contacts.UpdateRequest) (*contacts.Contact, error)

Update updates a contact.

type ContextOptions added in v0.1.4

type ContextOptions struct {
	RequestID      string
	Debug          bool
	UserAgent      string
	IdempotencyKey string
	Timeout        time.Duration
}

ContextOptions configures context with multiple options at once.

type CredentialsService added in v0.1.3

type CredentialsService service

CredentialsService handles credential operations.

func (*CredentialsService) Create added in v0.1.3

Create creates a new credential for a provider.

func (*CredentialsService) Delete added in v0.1.3

func (s *CredentialsService) Delete(ctx context.Context, provider connectors.Provider, credentialID string) error

Delete deletes a credential.

func (*CredentialsService) Get added in v0.1.3

func (s *CredentialsService) Get(ctx context.Context, provider connectors.Provider, credentialID string) (*credentials.Credential, error)

Get returns a single credential by ID.

func (*CredentialsService) List added in v0.1.3

List returns all credentials for a provider.

func (*CredentialsService) ListAll added in v0.1.3

ListAll returns an iterator for all credentials for a provider.

func (*CredentialsService) Update added in v0.1.3

func (s *CredentialsService) Update(ctx context.Context, provider connectors.Provider, credentialID string, update *credentials.UpdateRequest) (*credentials.Credential, error)

Update updates a credential.

type DraftsService

type DraftsService service

DraftsService handles operations on email drafts.

func (*DraftsService) Create

func (s *DraftsService) Create(ctx context.Context, grantID string, create *drafts.CreateRequest) (*drafts.Draft, error)

Create creates a new draft.

func (*DraftsService) Delete

func (s *DraftsService) Delete(ctx context.Context, grantID, draftID string) error

Delete deletes a draft.

func (*DraftsService) Get

func (s *DraftsService) Get(ctx context.Context, grantID, draftID string) (*drafts.Draft, error)

Get returns a single draft.

func (*DraftsService) List

func (s *DraftsService) List(ctx context.Context, grantID string, opts *drafts.ListOptions) (*ListResponse[drafts.Draft], error)

List returns drafts for a grant.

func (*DraftsService) ListAll

func (s *DraftsService) ListAll(ctx context.Context, grantID string, opts *drafts.ListOptions) *Iterator[drafts.Draft]

ListAll returns an iterator for all drafts.

func (*DraftsService) Send

func (s *DraftsService) Send(ctx context.Context, grantID, draftID string) (*drafts.Draft, error)

Send sends a draft as an email message.

func (*DraftsService) Update

func (s *DraftsService) Update(ctx context.Context, grantID, draftID string, update *drafts.UpdateRequest) (*drafts.Draft, error)

Update updates a draft.

type EventsService

type EventsService service

EventsService handles operations on calendar events.

func (*EventsService) Create added in v0.1.2

func (s *EventsService) Create(ctx context.Context, grantID, calendarID string, create *events.CreateRequest) (*events.Event, error)

Create creates a new event.

Example - simple event:

event, err := client.Events.Create(ctx, grantID, "primary", &events.CreateRequest{
    Title: "Team Meeting",
    When: events.When{
        StartTime: nylas.Ptr(time.Now().Add(24 * time.Hour).Unix()),
        EndTime:   nylas.Ptr(time.Now().Add(25 * time.Hour).Unix()),
    },
})

Example - event with Google Meet and participants:

event, err := client.Events.Create(ctx, grantID, "primary", &events.CreateRequest{
    Title:       "Project Sync",
    Description: "Weekly project status update",
    When: events.When{
        StartTime: nylas.Ptr(startTime.Unix()),
        EndTime:   nylas.Ptr(endTime.Unix()),
    },
    Participants: []events.Participant{
        {Email: "alice@example.com", Name: "Alice"},
        {Email: "bob@example.com", Name: "Bob"},
    },
    Conferencing: &events.Conferencing{
        Provider: "Google Meet",
        Autocreate: &events.AutocreateConfig{},
    },
})

Example - recurring event (every weekday):

event, err := client.Events.Create(ctx, grantID, "primary", &events.CreateRequest{
    Title: "Daily Standup",
    When: events.When{
        StartTime: nylas.Ptr(startTime.Unix()),
        EndTime:   nylas.Ptr(endTime.Unix()),
    },
    Recurrence: &events.Recurrence{
        RRule: []string{"RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR"},
    },
})
Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/mqasimca/nylas-go"
	"github.com/mqasimca/nylas-go/events"
)

func main() {
	client, _ := nylas.NewClient(nylas.WithAPIKey("your-api-key"))
	ctx := context.Background()
	grantID := "your-grant-id"
	calendarID := "primary"

	// Create a calendar event
	event, err := client.Events.Create(ctx, grantID, calendarID, &events.CreateRequest{
		Title:       "Team Meeting",
		Description: "Weekly sync with the team",
		When: events.When{
			StartTime: nylas.Ptr(int64(1704067200)), // Unix timestamp
			EndTime:   nylas.Ptr(int64(1704070800)),
		},
		Participants: []events.Participant{
			{Email: "colleague@example.com", Name: "Colleague"},
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Created event: %s\n", event.ID)
}

func (*EventsService) Delete added in v0.1.2

func (s *EventsService) Delete(ctx context.Context, grantID, eventID, calendarID string) error

Delete deletes an event.

func (*EventsService) Get added in v0.1.2

func (s *EventsService) Get(ctx context.Context, grantID, eventID string, calendarID string) (*events.Event, error)

Get returns a single event.

func (*EventsService) Import added in v0.1.3

func (s *EventsService) Import(ctx context.Context, grantID string, opts *events.ImportOptions) (*ListResponse[events.Event], error)

Import returns events from a calendar including recurring event instances with their parent events and any overrides. This is useful for working with recurring events as it returns the complete recurrence information.

func (*EventsService) ImportAll added in v0.1.3

func (s *EventsService) ImportAll(ctx context.Context, grantID string, opts *events.ImportOptions) *Iterator[events.Event]

ImportAll returns an iterator for importing all events from a calendar.

func (*EventsService) List added in v0.1.2

func (s *EventsService) List(ctx context.Context, grantID string, opts *events.ListOptions) (*ListResponse[events.Event], error)

List returns events for a grant.

Use ListOptions to filter by calendar, time range, or other criteria.

Example:

// List events for the next 7 days
now := time.Now()
resp, err := client.Events.List(ctx, grantID, &events.ListOptions{
    CalendarID: "primary",
    Start:      nylas.Ptr(now.Unix()),
    End:        nylas.Ptr(now.Add(7 * 24 * time.Hour).Unix()),
    Limit:      nylas.Ptr(50),
})

func (*EventsService) ListAll added in v0.1.2

func (s *EventsService) ListAll(ctx context.Context, grantID string, opts *events.ListOptions) *Iterator[events.Event]

ListAll returns an iterator for all events.

func (*EventsService) SendRSVP added in v0.1.2

func (s *EventsService) SendRSVP(ctx context.Context, grantID, eventID, calendarID string, rsvp *events.RSVPRequest) error

SendRSVP sends an RSVP response for an event.

Use this to accept, decline, or tentatively accept an event invitation.

Example:

// Accept an invitation
err := client.Events.SendRSVP(ctx, grantID, eventID, calendarID, &events.RSVPRequest{
    Status: "yes",
})

// Decline with a message
err := client.Events.SendRSVP(ctx, grantID, eventID, calendarID, &events.RSVPRequest{
    Status:  "no",
    Comment: "I have a conflict at this time.",
})

func (*EventsService) Update added in v0.1.2

func (s *EventsService) Update(ctx context.Context, grantID, eventID, calendarID string, update *events.UpdateRequest) (*events.Event, error)

Update updates an event.

Only fields that are set in the UpdateRequest will be modified.

Example - reschedule an event:

event, err := client.Events.Update(ctx, grantID, eventID, calendarID, &events.UpdateRequest{
    When: &events.When{
        StartTime: nylas.Ptr(newStartTime.Unix()),
        EndTime:   nylas.Ptr(newEndTime.Unix()),
    },
})

Example - update title and add a participant:

event, err := client.Events.Update(ctx, grantID, eventID, calendarID, &events.UpdateRequest{
    Title: nylas.Ptr("Updated Meeting Title"),
    Participants: []events.Participant{
        {Email: "newattendee@example.com", Name: "New Attendee"},
    },
})

type FoldersService

type FoldersService service

FoldersService handles operations on email folders/labels.

func (*FoldersService) Create added in v0.1.2

func (s *FoldersService) Create(ctx context.Context, grantID string, create *folders.CreateRequest) (*folders.Folder, error)

Create creates a new folder.

func (*FoldersService) Delete added in v0.1.2

func (s *FoldersService) Delete(ctx context.Context, grantID, folderID string) error

Delete deletes a folder.

func (*FoldersService) Get added in v0.1.2

func (s *FoldersService) Get(ctx context.Context, grantID, folderID string) (*folders.Folder, error)

Get returns a single folder.

func (*FoldersService) List added in v0.1.2

List returns folders for a grant.

func (*FoldersService) ListAll added in v0.1.2

func (s *FoldersService) ListAll(ctx context.Context, grantID string, opts *folders.ListOptions) *Iterator[folders.Folder]

ListAll returns an iterator for all folders.

func (*FoldersService) Update added in v0.1.2

func (s *FoldersService) Update(ctx context.Context, grantID, folderID string, update *folders.UpdateRequest) (*folders.Folder, error)

Update updates a folder.

type GrantsService

type GrantsService service

GrantsService handles operations on connected accounts (grants).

func (*GrantsService) Delete added in v0.1.2

func (s *GrantsService) Delete(ctx context.Context, grantID string) error

Delete deletes a grant.

func (*GrantsService) Get added in v0.1.2

func (s *GrantsService) Get(ctx context.Context, grantID string) (*grants.Grant, error)

Get returns a single grant.

func (*GrantsService) List added in v0.1.2

List returns all grants.

func (*GrantsService) ListAll added in v0.1.3

ListAll returns an iterator for all grants using offset-based pagination.

func (*GrantsService) Update added in v0.1.2

func (s *GrantsService) Update(ctx context.Context, grantID string, update *grants.UpdateRequest) (*grants.Grant, error)

Update updates a grant.

type HTTPTransportConfig added in v0.1.4

type HTTPTransportConfig struct {
	MaxIdleConns        int           // Maximum idle connections across all hosts (default: 100)
	MaxIdleConnsPerHost int           // Maximum idle connections per host (default: 2, recommend 10+ for high throughput)
	IdleConnTimeout     time.Duration // How long idle connections stay open (default: 90s)
	TLSHandshakeTimeout time.Duration // TLS handshake timeout (default: 10s)
}

HTTPTransportConfig holds configuration for the HTTP transport layer.

type Iterator

type Iterator[T any] struct {
	// contains filtered or unexported fields
}

Iterator provides paginated iteration over API resources. Use Next() to get items one at a time, or Collect() to get all items at once.

Example:

iter := client.Messages.ListAll(ctx, grantID, nil)
for {
    msg, err := iter.Next()
    if errors.Is(err, nylas.ErrDone) {
        break
    }
    if err != nil {
        return err
    }
    process(msg)
}
Example
package main

import (
	"context"
	"errors"
	"fmt"
	"log"

	"github.com/mqasimca/nylas-go"
)

func main() {
	client, _ := nylas.NewClient(nylas.WithAPIKey("your-api-key"))
	ctx := context.Background()
	grantID := "your-grant-id"

	// Iterate through all messages
	iter := client.Messages.ListAll(ctx, grantID, nil)
	for {
		msg, err := iter.Next()
		if errors.Is(err, nylas.ErrDone) {
			break // No more messages
		}
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("Message: %s\n", msg.Subject)
	}
}

func NewIterator

func NewIterator[T any](ctx context.Context, fetch func(context.Context, string) ([]T, string, error)) *Iterator[T]

NewIterator creates a new Iterator with the given fetch function.

func (*Iterator[T]) Collect

func (it *Iterator[T]) Collect() ([]*T, error)

Collect returns all remaining items as a slice. Useful when you need all items at once.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/mqasimca/nylas-go"
	"github.com/mqasimca/nylas-go/messages"
)

func main() {
	client, _ := nylas.NewClient(nylas.WithAPIKey("your-api-key"))
	ctx := context.Background()
	grantID := "your-grant-id"

	// Collect all messages at once
	iter := client.Messages.ListAll(ctx, grantID, &messages.ListOptions{
		Limit: nylas.Ptr(100),
	})

	allMessages, err := iter.Collect()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found %d messages\n", len(allMessages))
}

func (*Iterator[T]) Next

func (it *Iterator[T]) Next() (*T, error)

Next returns the next item in the iteration. Returns ErrDone when there are no more items.

func (*Iterator[T]) Reset

func (it *Iterator[T]) Reset()

Reset clears the iterator state, allowing iteration to start over from the beginning.

type ListResponse

type ListResponse[T any] struct {
	Data       []T    `json:"data"`
	RequestID  string `json:"request_id"`
	NextCursor string `json:"next_cursor,omitempty"`
}

ListResponse wraps a paginated list response from the Nylas API.

type LogLevel added in v0.1.4

type LogLevel int

LogLevel represents the severity level for logging.

const (
	// LogLevelDebug enables all log messages.
	LogLevelDebug LogLevel = iota
	// LogLevelInfo enables info, warn, and error messages.
	LogLevelInfo
	// LogLevelWarn enables warn and error messages.
	LogLevelWarn
	// LogLevelError enables only error messages.
	LogLevelError
	// LogLevelNone disables all logging.
	LogLevelNone
)

type Logger added in v0.1.4

type Logger interface {
	// Debug logs debug-level messages (detailed information for debugging).
	Debug(ctx context.Context, msg string, fields ...any)
	// Info logs informational messages (general information).
	Info(ctx context.Context, msg string, fields ...any)
	// Warn logs warning messages (something unexpected but not an error).
	Warn(ctx context.Context, msg string, fields ...any)
	// Error logs error messages (errors that occurred).
	Error(ctx context.Context, msg string, fields ...any)
}

Logger is the interface for logging within the SDK. Implement this interface to integrate with your logging framework.

type MessagesService

type MessagesService service

MessagesService handles operations on email messages.

func (*MessagesService) Clean

Clean extracts clean conversation text from messages.

This removes quoted text, signatures, and other noise to get the core message content. Useful for AI processing, summarization, or displaying clean conversation threads.

func (*MessagesService) Delete

func (s *MessagesService) Delete(ctx context.Context, grantID, messageID string) error

Delete permanently removes a message.

The grantID is the ID of the connected account. The messageID is the unique identifier of the message to delete. This action cannot be undone. Consider moving to trash instead.

func (*MessagesService) Get

func (s *MessagesService) Get(ctx context.Context, grantID, messageID string) (*messages.Message, error)

Get returns a single message by ID.

The grantID is the ID of the connected account. The messageID is the unique identifier of the message to retrieve. Returns ErrNotFound if the message does not exist.

func (*MessagesService) GetScheduled

func (s *MessagesService) GetScheduled(ctx context.Context, grantID, scheduleID string) (*messages.ScheduledMessage, error)

GetScheduled returns details about a specific scheduled message.

The scheduleID is obtained from ListScheduled or the response when scheduling a message.

func (*MessagesService) List

List returns messages for a grant with optional filtering.

The grantID is the ID of the connected account (obtained via OAuth). Use opts to filter messages by sender, recipient, subject, date range, etc. Returns a paginated response; use NextCursor for pagination or ListAll for iteration.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/mqasimca/nylas-go"
	"github.com/mqasimca/nylas-go/messages"
)

func main() {
	client, _ := nylas.NewClient(nylas.WithAPIKey("your-api-key"))
	ctx := context.Background()
	grantID := "your-grant-id"

	// List messages with filtering
	resp, err := client.Messages.List(ctx, grantID, &messages.ListOptions{
		Limit:  nylas.Ptr(10),
		Unread: nylas.Ptr(true),
	})
	if err != nil {
		log.Fatal(err)
	}

	for _, msg := range resp.Data {
		fmt.Printf("Subject: %s\n", msg.Subject)
	}
}

func (*MessagesService) ListAll

ListAll returns an iterator that automatically paginates through all messages.

Use Next() to retrieve messages one at a time, or Collect() to get all at once. The iterator handles pagination automatically using the NextCursor from each response.

func (*MessagesService) ListScheduled

func (s *MessagesService) ListScheduled(ctx context.Context, grantID string) (messages.ScheduledMessagesList, error)

ListScheduled returns all messages scheduled for future delivery.

Scheduled messages were created with SendAt set to a future timestamp. Use StopScheduled to cancel a scheduled message before it's sent.

func (*MessagesService) Send

func (s *MessagesService) Send(ctx context.Context, grantID string, send *messages.SendRequest) (*messages.Message, error)

Send sends a new email message immediately.

The grantID is the ID of the connected account to send from. At minimum, the To field and either Subject or Body must be provided. To schedule a message for later delivery, set SendAt to a future Unix timestamp.

Automatically uses multipart/form-data encoding when total attachment size >= 3MB (per Nylas API v3 requirements). For smaller attachments, uses standard JSON encoding.

Returns the sent message with its assigned ID.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/mqasimca/nylas-go"
	"github.com/mqasimca/nylas-go/messages"
)

func main() {
	client, _ := nylas.NewClient(nylas.WithAPIKey("your-api-key"))
	ctx := context.Background()
	grantID := "your-grant-id"

	// Send an email
	msg, err := client.Messages.Send(ctx, grantID, &messages.SendRequest{
		To:      []messages.Participant{{Email: "recipient@example.com"}},
		Subject: "Hello from Nylas",
		Body:    "<h1>Hello!</h1><p>This is a test email.</p>",
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Sent message ID: %s\n", msg.ID)
}
Example (WithAttachment)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/mqasimca/nylas-go"
	"github.com/mqasimca/nylas-go/messages"
)

func main() {
	client, _ := nylas.NewClient(nylas.WithAPIKey("your-api-key"))
	ctx := context.Background()
	grantID := "your-grant-id"

	// Send email with attachment
	// SDK automatically uses multipart for attachments >= 3MB
	msg, err := client.Messages.Send(ctx, grantID, &messages.SendRequest{
		To:      []messages.Participant{{Email: "recipient@example.com"}},
		Subject: "Invoice",
		Body:    "Please find attached invoice.",
		Attachments: []messages.AttachmentRequest{
			{
				Filename:    "invoice.pdf",
				ContentType: "application/pdf",
				Content:     "base64-encoded-content-here",
			},
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Sent message with attachment: %s\n", msg.ID)
}

func (*MessagesService) StopScheduled

func (s *MessagesService) StopScheduled(ctx context.Context, grantID, scheduleID string) error

StopScheduled cancels a scheduled message before it's sent.

The message will not be sent and cannot be recovered after cancellation.

func (*MessagesService) Update

func (s *MessagesService) Update(ctx context.Context, grantID, messageID string, update *messages.UpdateRequest) (*messages.Message, error)

Update modifies a message's metadata (read status, starred, folders).

The grantID is the ID of the connected account. The messageID is the unique identifier of the message to update. Only the fields specified in the UpdateRequest are modified.

type Middleware added in v0.1.4

type Middleware func(http.RoundTripper) http.RoundTripper

Middleware is a function that wraps an http.RoundTripper to add custom behavior. Middleware can be used for logging, metrics, request transformation, etc.

Example logging middleware:

func LoggingMiddleware(next http.RoundTripper) http.RoundTripper {
    return RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
        log.Printf("Request: %s %s", req.Method, req.URL)
        resp, err := next.RoundTrip(req)
        if err != nil {
            log.Printf("Error: %v", err)
        } else {
            log.Printf("Response: %d", resp.StatusCode)
        }
        return resp, err
    })
}

func HeaderMiddleware added in v0.1.4

func HeaderMiddleware(headers map[string]string) Middleware

HeaderMiddleware creates middleware that adds custom headers to all requests.

func MetricsMiddleware added in v0.1.4

func MetricsMiddleware(onRequest func(method, path string, duration int64, statusCode int, err error)) Middleware

MetricsMiddleware creates middleware for collecting request metrics.

func RequestIDMiddleware added in v0.1.4

func RequestIDMiddleware(generateID func() string) Middleware

RequestIDMiddleware creates middleware that adds a request ID to all requests.

func RetryMiddleware added in v0.1.4

func RetryMiddleware(maxRetries int, shouldRetry func(*http.Response, error) bool) Middleware

RetryMiddleware creates middleware that retries failed requests. This is useful when you want custom retry logic beyond the SDK's built-in retry.

type NeuralService added in v0.1.4

type NeuralService service

NeuralService handles ML-powered email intelligence operations.

func (*NeuralService) Categorize added in v0.1.4

func (s *NeuralService) Categorize(ctx context.Context, grantID, messageID string) (*neural.CategorizeResponse, error)

Categorize classifies a message as conversation (human-to-human) or feed (automated).

This uses machine learning to determine if a message is a personal conversation or an automated feed (newsletters, notifications, etc.).

Requires Nylas Plus plan or higher.

func (*NeuralService) CategorizeBatch added in v0.1.4

func (s *NeuralService) CategorizeBatch(ctx context.Context, grantID string, messageIDs []string) ([]*neural.CategorizeResponse, error)

CategorizeBatch categorizes multiple messages concurrently.

This is a convenience method that calls Categorize for each message in parallel with a concurrency limit of 10.

func (*NeuralService) CleanConversation added in v0.1.4

func (s *NeuralService) CleanConversation(ctx context.Context, grantID, messageID string, opts *neural.CleanConversationRequest) (*neural.CleanConversationResponse, error)

CleanConversation extracts clean message body without signatures, quotes, and formatting.

This removes email signatures, quoted replies, and other non-conversation content to extract just the core message.

Requires Nylas Plus plan or higher.

func (*NeuralService) ExtractSignature added in v0.1.4

func (s *NeuralService) ExtractSignature(ctx context.Context, grantID, messageID string, opts *neural.SignatureExtractionRequest) (*neural.SignatureExtractionResponse, error)

ExtractSignature extracts email signature and optionally parses contact information.

This identifies and extracts the email signature portion of a message. If ParseContacts is enabled, it also extracts structured contact information like name, email, phone, job title, and company.

Requires Nylas Plus plan or higher.

func (*NeuralService) ExtractText added in v0.1.4

func (s *NeuralService) ExtractText(ctx context.Context, grantID, messageID string, opts *neural.OCRRequest) (*neural.OCRResponse, error)

ExtractText performs OCR to extract text from images in an email.

This analyzes images and attachments in the message to extract any text content.

Requires Nylas Plus plan or higher.

type NoopLogger added in v0.1.4

type NoopLogger struct{}

NoopLogger is a logger that does nothing. Use this to disable logging completely.

func (*NoopLogger) Debug added in v0.1.4

func (l *NoopLogger) Debug(ctx context.Context, msg string, fields ...any)

func (*NoopLogger) Error added in v0.1.4

func (l *NoopLogger) Error(ctx context.Context, msg string, fields ...any)

func (*NoopLogger) Info added in v0.1.4

func (l *NoopLogger) Info(ctx context.Context, msg string, fields ...any)

func (*NoopLogger) Warn added in v0.1.4

func (l *NoopLogger) Warn(ctx context.Context, msg string, fields ...any)

type NotetakersService

type NotetakersService service

NotetakersService handles notetaker operations.

func (*NotetakersService) Cancel added in v0.1.3

func (s *NotetakersService) Cancel(ctx context.Context, grantID, notetakerID string) error

Cancel cancels a scheduled notetaker before it joins the meeting.

func (*NotetakersService) Create added in v0.1.3

func (s *NotetakersService) Create(ctx context.Context, grantID string, createReq *notetakers.CreateRequest) (*notetakers.Notetaker, error)

Create invites a notetaker to join a meeting. If JoinTime is not specified, the notetaker will attempt to join immediately.

func (*NotetakersService) Get added in v0.1.3

func (s *NotetakersService) Get(ctx context.Context, grantID, notetakerID string) (*notetakers.Notetaker, error)

Get retrieves a single notetaker by ID.

func (*NotetakersService) GetHistory added in v0.1.3

func (s *NotetakersService) GetHistory(ctx context.Context, grantID, notetakerID string) (*notetakers.History, error)

GetHistory retrieves the event history for a notetaker. The history provides a timeline of everything that happened during the session.

func (*NotetakersService) GetMedia added in v0.1.3

func (s *NotetakersService) GetMedia(ctx context.Context, grantID, notetakerID string) ([]notetakers.Media, error)

GetMedia retrieves media files (recordings, transcripts) for a notetaker.

func (*NotetakersService) Leave added in v0.1.3

func (s *NotetakersService) Leave(ctx context.Context, grantID, notetakerID string) error

Leave removes a notetaker from an active meeting.

func (*NotetakersService) List added in v0.1.3

List returns all notetakers for a grant.

func (*NotetakersService) ListAll added in v0.1.3

ListAll returns an iterator for all notetakers.

type Option

type Option func(*Client)

Option is a functional option for configuring the Client.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sets the API key for authentication.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL sets a custom base URL for the API. Useful for testing or proxying.

func WithCircuitBreaker added in v0.1.4

func WithCircuitBreaker(config CircuitBreakerConfig) Option

WithCircuitBreaker enables circuit breaker pattern to prevent cascading failures. The circuit breaker will trip (stop requests) after repeated failures and will attempt to recover after a timeout period.

Example with default config:

client, _ := nylas.NewClient(
    nylas.WithAPIKey("key"),
    nylas.WithCircuitBreaker(nylas.DefaultCircuitBreakerConfig()),
)

Example with custom config:

config := nylas.CircuitBreakerConfig{
    MaxRequests: 2,           // Allow 2 requests in half-open state
    Timeout:     30 * time.Second,  // Try to recover after 30s
    ReadyToTrip: func(counts gobreaker.Counts) bool {
        // Trip after 3 consecutive failures
        return counts.ConsecutiveFailures >= 3
    },
    OnStateChange: func(name string, from gobreaker.State, to gobreaker.State) {
        log.Printf("Circuit breaker %s: %s -> %s", name, from, to)
    },
}
client, _ := nylas.NewClient(
    nylas.WithAPIKey("key"),
    nylas.WithCircuitBreaker(config),
)

func WithDisableJitter added in v0.1.4

func WithDisableJitter(disable bool) Option

WithDisableJitter disables jitter in retry backoff calculations. By default, jitter is enabled to avoid thundering herd problems.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient sets a custom HTTP client for making requests.

func WithHTTPTransport added in v0.1.4

func WithHTTPTransport(config HTTPTransportConfig) Option

WithHTTPTransport configures the HTTP transport connection pool settings. This is useful for tuning performance in high-throughput scenarios.

Example:

client, _ := nylas.NewClient(
    nylas.WithAPIKey("key"),
    nylas.WithHTTPTransport(nylas.HTTPTransportConfig{
        MaxIdleConnsPerHost: 20,  // Allow 20 idle connections per host
        IdleConnTimeout:     120 * time.Second,
    }),
)

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets the maximum number of retry attempts for failed requests.

func WithMaxRetryWait added in v0.1.4

func WithMaxRetryWait(d time.Duration) Option

WithMaxRetryWait sets the maximum wait time for retries (caps exponential backoff).

func WithRateLimitWarningThreshold added in v0.1.4

func WithRateLimitWarningThreshold(threshold float64) Option

WithRateLimitWarningThreshold sets the threshold for automatic rate limit warnings. When remaining requests drop below this percentage (0.0-1.0), rate limit observers will see the updated rate. Combine with OnRateLimit to implement custom warning logic.

func WithRegion

func WithRegion(region Region) Option

WithRegion sets the API region (US or EU).

func WithRetryWait

func WithRetryWait(d time.Duration) Option

WithRetryWait sets the base wait time between retries (uses exponential backoff).

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the HTTP client timeout.

type QueryBuilder added in v0.1.4

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

QueryBuilder provides a fluent API for building query parameters. It's useful for constructing complex filter and search queries.

Example:

q := nylas.NewQueryBuilder().
    In("folder_id", []string{"inbox", "sent"}).
    Subject("important").
    From("boss@company.com").
    Unread(true).
    Limit(50)
values := q.Values()

func ContactQuery added in v0.1.4

func ContactQuery() *QueryBuilder

ContactQuery creates a query builder pre-configured for contact filtering.

func EventQuery added in v0.1.4

func EventQuery() *QueryBuilder

EventQuery creates a query builder pre-configured for event filtering.

func MessageQuery added in v0.1.4

func MessageQuery() *QueryBuilder

MessageQuery creates a query builder pre-configured for message filtering.

func NewQueryBuilder added in v0.1.4

func NewQueryBuilder() *QueryBuilder

NewQueryBuilder creates a new query builder.

func (*QueryBuilder) Add added in v0.1.4

func (q *QueryBuilder) Add(key, value string) *QueryBuilder

Add adds a parameter value, preserving existing values.

func (*QueryBuilder) After added in v0.1.4

func (q *QueryBuilder) After(timestamp int64) *QueryBuilder

After filters messages received after this Unix timestamp.

func (*QueryBuilder) Before added in v0.1.4

func (q *QueryBuilder) Before(timestamp int64) *QueryBuilder

Before filters messages received before this Unix timestamp.

func (*QueryBuilder) CalendarID added in v0.1.4

func (q *QueryBuilder) CalendarID(id string) *QueryBuilder

CalendarID filters events by calendar ID.

func (*QueryBuilder) Clone added in v0.1.4

func (q *QueryBuilder) Clone() *QueryBuilder

Clone creates a deep copy of the query builder. Useful for building multiple similar queries from a base.

func (*QueryBuilder) Del added in v0.1.4

func (q *QueryBuilder) Del(key string) *QueryBuilder

Del removes a parameter.

func (*QueryBuilder) Encode added in v0.1.4

func (q *QueryBuilder) Encode() string

Encode returns the URL-encoded query string.

func (*QueryBuilder) EndTime added in v0.1.4

func (q *QueryBuilder) EndTime(timestamp int64) *QueryBuilder

EndTime filters events ending before this Unix timestamp.

func (*QueryBuilder) From added in v0.1.4

func (q *QueryBuilder) From(email string) *QueryBuilder

From filters messages by sender email address.

func (*QueryBuilder) Get added in v0.1.4

func (q *QueryBuilder) Get(key string) string

Get returns the first value for the parameter.

func (*QueryBuilder) Has added in v0.1.4

func (q *QueryBuilder) Has(key string) bool

Has returns true if the parameter exists.

func (*QueryBuilder) HasAttachment added in v0.1.4

func (q *QueryBuilder) HasAttachment(has bool) *QueryBuilder

HasAttachment filters messages that have attachments.

func (*QueryBuilder) In added in v0.1.4

func (q *QueryBuilder) In(key string, values []string) *QueryBuilder

In sets a parameter to match any of the provided values. For array parameters like folder_id, calendar_id, etc.

func (*QueryBuilder) Limit added in v0.1.4

func (q *QueryBuilder) Limit(limit int) *QueryBuilder

Limit sets the maximum number of results to return.

func (*QueryBuilder) Metadata added in v0.1.4

func (q *QueryBuilder) Metadata(key, value string) *QueryBuilder

Metadata filters resources by metadata key-value pairs. For multiple pairs, call this method multiple times.

func (*QueryBuilder) OrderBy added in v0.1.4

func (q *QueryBuilder) OrderBy(field string, desc bool) *QueryBuilder

OrderBy sets the field to order results by.

func (*QueryBuilder) PageToken added in v0.1.4

func (q *QueryBuilder) PageToken(token string) *QueryBuilder

PageToken sets the pagination cursor.

func (*QueryBuilder) Reset added in v0.1.4

func (q *QueryBuilder) Reset() *QueryBuilder

Reset clears all parameters.

func (*QueryBuilder) SearchQuery added in v0.1.4

func (q *QueryBuilder) SearchQuery(query string) *QueryBuilder

SearchQuery sets a free-text search query.

func (*QueryBuilder) Select added in v0.1.4

func (q *QueryBuilder) Select(fields ...string) *QueryBuilder

Select specifies which fields to include in the response.

func (*QueryBuilder) Set added in v0.1.4

func (q *QueryBuilder) Set(key, value string) *QueryBuilder

Set sets a parameter to a single value, replacing any existing values.

func (*QueryBuilder) Starred added in v0.1.4

func (q *QueryBuilder) Starred(starred bool) *QueryBuilder

Starred filters messages by starred status.

func (*QueryBuilder) StartTime added in v0.1.4

func (q *QueryBuilder) StartTime(timestamp int64) *QueryBuilder

StartTime filters events starting after this Unix timestamp.

func (*QueryBuilder) Subject added in v0.1.4

func (q *QueryBuilder) Subject(subject string) *QueryBuilder

Subject filters messages by subject (contains match).

func (*QueryBuilder) To added in v0.1.4

func (q *QueryBuilder) To(email string) *QueryBuilder

To filters messages by recipient email address.

func (*QueryBuilder) Unread added in v0.1.4

func (q *QueryBuilder) Unread(unread bool) *QueryBuilder

Unread filters messages by read/unread status.

func (*QueryBuilder) Values added in v0.1.4

func (q *QueryBuilder) Values() url.Values

Values returns the built query parameters as url.Values.

type QueryValues

type QueryValues interface {
	Values() map[string]any
}

QueryValues is an interface for types that can convert to query parameters.

type QuotaExceededError added in v0.1.4

type QuotaExceededError struct {
	APIError
	QuotaType string `json:"quota_type,omitempty"`
	Limit     int64  `json:"limit,omitempty"`
	Usage     int64  `json:"usage,omitempty"`
	ResetTime int64  `json:"reset_time,omitempty"`
}

QuotaExceededError represents a quota or limit exceeded error.

func (*QuotaExceededError) Error added in v0.1.4

func (e *QuotaExceededError) Error() string

Error implements the error interface.

type Rate

type Rate struct {
	Limit     int       // Maximum requests allowed in the window
	Remaining int       // Requests remaining in the current window
	Reset     time.Time // When the rate limit window resets
}

Rate contains rate limit information from the Nylas API.

func (Rate) IsNearLimit added in v0.1.4

func (r Rate) IsNearLimit(threshold float64) bool

IsNearLimit returns true if remaining requests are below the given percentage threshold. For example, threshold=0.2 returns true when less than 20% of requests remain.

type RateLimitError

type RateLimitError struct {
	Rate    Rate
	Message string
}

RateLimitError is returned when the API rate limit is exceeded.

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

Error implements the error interface.

type RateLimitObserver added in v0.1.4

type RateLimitObserver func(rate Rate)

RateLimitObserver is called when rate limit information is updated from an API response. Use this to monitor rate limit consumption and implement custom alerting or throttling.

type RedirectURIsService added in v0.1.3

type RedirectURIsService service

RedirectURIsService handles redirect URI operations.

func (*RedirectURIsService) Create added in v0.1.3

Create creates a new redirect URI.

func (*RedirectURIsService) Delete added in v0.1.3

func (s *RedirectURIsService) Delete(ctx context.Context, redirectURIID string) error

Delete deletes a redirect URI.

func (*RedirectURIsService) Get added in v0.1.3

func (s *RedirectURIsService) Get(ctx context.Context, redirectURIID string) (*redirecturis.RedirectURI, error)

Get returns a single redirect URI by ID.

func (*RedirectURIsService) List added in v0.1.3

List returns all redirect URIs for the application.

func (*RedirectURIsService) ListAll added in v0.1.3

ListAll returns an iterator for all redirect URIs.

func (*RedirectURIsService) Update added in v0.1.3

Update updates a redirect URI.

type Region

type Region string

Region represents a Nylas API region.

const (
	RegionUS Region = "us" // United States (default)
	RegionEU Region = "eu" // European Union
)

Available Nylas API regions.

type Response

type Response[T any] struct {
	Data      T      `json:"data"`
	RequestID string `json:"request_id"`
}

Response wraps a single resource response from the Nylas API.

type RoundTripperFunc added in v0.1.4

type RoundTripperFunc func(*http.Request) (*http.Response, error)

RoundTripperFunc is an adapter to allow the use of ordinary functions as http.RoundTrippers.

func (RoundTripperFunc) RoundTrip added in v0.1.4

func (f RoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements the http.RoundTripper interface.

type SchedulerService

type SchedulerService service

SchedulerService handles scheduling operations.

func (*SchedulerService) CancelBooking added in v0.1.3

func (s *SchedulerService) CancelBooking(ctx context.Context, configID, bookingID, reason string) error

CancelBooking cancels an existing booking.

func (*SchedulerService) ConfirmBooking added in v0.1.3

func (s *SchedulerService) ConfirmBooking(ctx context.Context, configID, bookingID string, confirm *scheduler.ConfirmBookingRequest) (*scheduler.Booking, error)

ConfirmBooking confirms or rejects a pending booking.

func (*SchedulerService) CreateBooking added in v0.1.3

func (s *SchedulerService) CreateBooking(ctx context.Context, configID string, bookingReq *scheduler.BookingRequest) (*scheduler.Booking, error)

CreateBooking creates a new booking for a configuration.

func (*SchedulerService) CreateConfiguration added in v0.1.3

func (s *SchedulerService) CreateConfiguration(ctx context.Context, grantID string, configReq *scheduler.ConfigurationRequest) (*scheduler.Configuration, error)

CreateConfiguration creates a new scheduler configuration.

func (*SchedulerService) CreateSession added in v0.1.3

func (s *SchedulerService) CreateSession(ctx context.Context, sessionReq *scheduler.SessionRequest) (*scheduler.Session, error)

CreateSession creates a new scheduler session for a configuration.

func (*SchedulerService) DeleteConfiguration added in v0.1.3

func (s *SchedulerService) DeleteConfiguration(ctx context.Context, grantID, configID string) error

DeleteConfiguration deletes a scheduler configuration.

func (*SchedulerService) DeleteSession added in v0.1.4

func (s *SchedulerService) DeleteSession(ctx context.Context, sessionID string) error

DeleteSession deletes a scheduler session.

func (*SchedulerService) GetAvailability added in v0.1.4

GetAvailability returns available time slots for a configuration.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/mqasimca/nylas-go"
	"github.com/mqasimca/nylas-go/scheduler"
)

func main() {
	client, _ := nylas.NewClient(nylas.WithAPIKey("your-api-key"))
	ctx := context.Background()

	// Get availability for a scheduler configuration
	availability, err := client.Scheduler.GetAvailability(ctx, &scheduler.AvailabilityRequest{
		ConfigurationID: "config-123",
		StartTime:       1704067200, // Start of week
		EndTime:         1704672000, // End of week
	})
	if err != nil {
		log.Fatal(err)
	}

	for _, slot := range availability.TimeSlots {
		fmt.Printf("Available slot: %d - %d\n", slot.StartTime, slot.EndTime)
	}
}

func (*SchedulerService) GetBooking added in v0.1.3

func (s *SchedulerService) GetBooking(ctx context.Context, configID, bookingID string) (*scheduler.Booking, error)

GetBooking retrieves a single booking by ID.

func (*SchedulerService) GetConfiguration added in v0.1.3

func (s *SchedulerService) GetConfiguration(ctx context.Context, grantID, configID string) (*scheduler.Configuration, error)

GetConfiguration retrieves a single scheduler configuration by ID.

func (*SchedulerService) ListBookings added in v0.1.3

ListBookings returns all bookings for a configuration.

func (*SchedulerService) ListConfigurations added in v0.1.3

ListConfigurations returns all scheduler configurations for a grant.

func (*SchedulerService) RescheduleBooking added in v0.1.3

func (s *SchedulerService) RescheduleBooking(ctx context.Context, configID, bookingID string, reschedule *scheduler.RescheduleBookingRequest) (*scheduler.Booking, error)

RescheduleBooking reschedules an existing booking.

func (*SchedulerService) UpdateConfiguration added in v0.1.3

func (s *SchedulerService) UpdateConfiguration(ctx context.Context, grantID, configID string, configReq *scheduler.ConfigurationRequest) (*scheduler.Configuration, error)

UpdateConfiguration updates an existing scheduler configuration.

type SmartComposeService added in v0.1.3

type SmartComposeService service

SmartComposeService handles AI-powered message composition.

func (*SmartComposeService) ComposeMessage added in v0.1.3

ComposeMessage generates a message suggestion based on a prompt.

func (*SmartComposeService) ComposeReply added in v0.1.3

func (s *SmartComposeService) ComposeReply(ctx context.Context, grantID, messageID string, compose *smartcompose.ComposeRequest) (*smartcompose.ComposeResponse, error)

ComposeReply generates a reply suggestion for an existing message.

type StdLogger added in v0.1.4

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

StdLogger is a simple logger that writes to standard output/error using Go's log package.

func NewStdLogger added in v0.1.4

func NewStdLogger(level LogLevel) *StdLogger

NewStdLogger creates a standard logger with the specified log level.

Example:

logger := nylas.NewStdLogger(nylas.LogLevelDebug)
client.SetLogger(logger)

func (*StdLogger) Debug added in v0.1.4

func (l *StdLogger) Debug(ctx context.Context, msg string, fields ...any)

func (*StdLogger) Error added in v0.1.4

func (l *StdLogger) Error(ctx context.Context, msg string, fields ...any)

func (*StdLogger) Info added in v0.1.4

func (l *StdLogger) Info(ctx context.Context, msg string, fields ...any)

func (*StdLogger) SetLevel added in v0.1.4

func (l *StdLogger) SetLevel(level LogLevel)

SetLevel changes the log level at runtime.

func (*StdLogger) Warn added in v0.1.4

func (l *StdLogger) Warn(ctx context.Context, msg string, fields ...any)

type StructuredLogger added in v0.1.4

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

StructuredLogger is a logger that outputs structured log entries. Implement this for JSON logging or other structured formats.

func NewStructuredLogger added in v0.1.4

func NewStructuredLogger(level LogLevel, output func(level string, msg string, fields map[string]any)) *StructuredLogger

NewStructuredLogger creates a structured logger with a custom output function.

Example:

logger := nylas.NewStructuredLogger(nylas.LogLevelInfo, func(level, msg string, fields map[string]any) {
    jsonData, _ := json.Marshal(map[string]any{
        "level":   level,
        "message": msg,
        "fields":  fields,
    })
    fmt.Println(string(jsonData))
})

func (*StructuredLogger) Debug added in v0.1.4

func (l *StructuredLogger) Debug(ctx context.Context, msg string, fields ...any)

func (*StructuredLogger) Error added in v0.1.4

func (l *StructuredLogger) Error(ctx context.Context, msg string, fields ...any)

func (*StructuredLogger) Info added in v0.1.4

func (l *StructuredLogger) Info(ctx context.Context, msg string, fields ...any)

func (*StructuredLogger) Warn added in v0.1.4

func (l *StructuredLogger) Warn(ctx context.Context, msg string, fields ...any)

type ThreadsService

type ThreadsService service

ThreadsService handles operations on email threads.

func (*ThreadsService) Delete

func (s *ThreadsService) Delete(ctx context.Context, grantID, threadID string) error

Delete deletes a thread.

func (*ThreadsService) Get

func (s *ThreadsService) Get(ctx context.Context, grantID, threadID string) (*threads.Thread, error)

Get returns a single thread.

func (*ThreadsService) List

List returns threads for a grant.

func (*ThreadsService) ListAll

func (s *ThreadsService) ListAll(ctx context.Context, grantID string, opts *threads.ListOptions) *Iterator[threads.Thread]

ListAll returns an iterator for all threads.

func (*ThreadsService) Update

func (s *ThreadsService) Update(ctx context.Context, grantID, threadID string, update *threads.UpdateRequest) (*threads.Thread, error)

Update updates a thread.

type ValidationError added in v0.1.4

type ValidationError struct {
	APIError
	Field      string `json:"field,omitempty"`
	Value      any    `json:"value,omitempty"`
	Constraint string `json:"constraint,omitempty"`
}

ValidationError represents a validation error from the API.

func (*ValidationError) Error added in v0.1.4

func (e *ValidationError) Error() string

Error implements the error interface.

type VirtualCalendarsService added in v0.1.4

type VirtualCalendarsService service

VirtualCalendarsService handles virtual calendar operations.

func (*VirtualCalendarsService) Create added in v0.1.4

Create creates a new virtual calendar.

The metadata field will automatically include "is_virtual":"true".

func (*VirtualCalendarsService) Delete added in v0.1.4

func (s *VirtualCalendarsService) Delete(ctx context.Context, grantID, calendarID string) error

Delete deletes a virtual calendar.

func (*VirtualCalendarsService) Get added in v0.1.4

Get retrieves a virtual calendar by ID.

func (*VirtualCalendarsService) List added in v0.1.4

List returns all virtual calendars for a grant.

Virtual calendars are regular calendars with metadata "is_virtual":"true".

func (*VirtualCalendarsService) ListAll added in v0.1.4

ListAll returns an iterator for all virtual calendars.

func (*VirtualCalendarsService) Update added in v0.1.4

Update updates a virtual calendar.

type WebhooksService

type WebhooksService service

WebhooksService handles operations on webhook subscriptions.

func (*WebhooksService) Create added in v0.1.2

Create creates a new webhook.

The webhook URL must be publicly accessible and respond to challenge requests. Nylas will send a GET request with a ?challenge= parameter that must be echoed back.

Example:

webhook, err := client.Webhooks.Create(ctx, &webhooks.CreateRequest{
    WebhookURL:   "https://yourapp.com/webhooks/nylas",
    TriggerTypes: []string{"message.created", "message.updated"},
    Description:  "Email notifications",
    NotificationEmailAddresses: []string{"alerts@yourcompany.com"},
})
if err != nil {
    return err
}
// Store webhook.WebhookSecret securely for signature verification

func (*WebhooksService) Delete added in v0.1.2

func (s *WebhooksService) Delete(ctx context.Context, webhookID string) error

Delete deletes a webhook.

func (*WebhooksService) Get added in v0.1.2

func (s *WebhooksService) Get(ctx context.Context, webhookID string) (*webhooks.Webhook, error)

Get returns a single webhook.

func (*WebhooksService) GetIPAddresses added in v0.1.3

func (s *WebhooksService) GetIPAddresses(ctx context.Context) (*webhooks.IPAddressesResponse, error)

GetIPAddresses returns the list of Nylas IP addresses used for sending webhooks. Use this to whitelist Nylas IPs in your firewall configuration. Note: This endpoint is available for paid customers only.

Example:

ips, err := client.Webhooks.GetIPAddresses(ctx)
if err != nil {
    return err
}
for _, ip := range ips.IPAddresses {
    fmt.Println("Whitelist:", ip)
}

func (*WebhooksService) List added in v0.1.2

List returns all webhooks.

func (*WebhooksService) ListAll added in v0.1.3

ListAll returns an iterator for all webhooks.

func (*WebhooksService) ParseWebhookEvent added in v0.1.4

func (s *WebhooksService) ParseWebhookEvent(body []byte, secret, signature string) (*webhooks.WebhookEvent, error)

ParseWebhookEvent parses and optionally verifies a webhook event. If both secret and signature are provided, signature verification is performed. Returns an error if signature verification fails or if the JSON cannot be parsed.

Example:

func handleWebhook(w http.ResponseWriter, r *http.Request) {
    body, _ := io.ReadAll(r.Body)
    signature := r.Header.Get("X-Nylas-Signature")

    event, err := client.Webhooks.ParseWebhookEvent(body, webhookSecret, signature)
    if err != nil {
        http.Error(w, "Invalid webhook", http.StatusUnauthorized)
        return
    }

    switch event.Type {
    case "message.created":
        // Handle new message event
    case "calendar.created":
        // Handle new calendar event
    }
}
Example
package main

import (
	"fmt"
	"log"

	"github.com/mqasimca/nylas-go"
)

func main() {
	client, _ := nylas.NewClient(nylas.WithAPIKey("your-api-key"))

	webhookSecret := "your-webhook-secret"
	signature := "signature-from-header"
	body := []byte(`{
		"specversion": "1.0",
		"type": "message.created",
		"id": "event-123",
		"data": {"id": "msg-456", "subject": "Hello"}
	}`)

	// Parse and verify webhook event
	event, err := client.Webhooks.ParseWebhookEvent(body, webhookSecret, signature)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Received webhook: %s (type: %s)\n", event.ID, event.Type)
}

func (*WebhooksService) RotateSecret added in v0.1.2

func (s *WebhooksService) RotateSecret(ctx context.Context, webhookID string) (*webhooks.RotateSecretResponse, error)

RotateSecret rotates a webhook's secret.

Use this periodically or after a suspected compromise to generate a new webhook secret. After rotation, update your webhook handler to use the new secret for signature verification.

Example:

result, err := client.Webhooks.RotateSecret(ctx, webhookID)
if err != nil {
    return err
}
// Update your stored secret with result.WebhookSecret

func (*WebhooksService) Update added in v0.1.2

func (s *WebhooksService) Update(ctx context.Context, webhookID string, update *webhooks.UpdateRequest) (*webhooks.Webhook, error)

Update updates a webhook.

Example:

webhook, err := client.Webhooks.Update(ctx, webhookID, &webhooks.UpdateRequest{
    TriggerTypes: []string{"message.created", "calendar.created"},
    Description:  "Updated webhook description",
})

func (*WebhooksService) VerifySignature added in v0.1.4

func (s *WebhooksService) VerifySignature(secret, signature string, body []byte) bool

VerifySignature verifies a webhook signature using HMAC-SHA256. The secret is your webhook secret (obtained from webhook creation/rotation). The signature is from the X-Nylas-Signature header in the webhook request. The body is the raw request body bytes. Returns true if the signature is valid, false otherwise.

Example:

func handleWebhook(w http.ResponseWriter, r *http.Request) {
    body, _ := io.ReadAll(r.Body)
    signature := r.Header.Get("X-Nylas-Signature")

    if !client.Webhooks.VerifySignature(webhookSecret, signature, body) {
        http.Error(w, "Invalid signature", http.StatusUnauthorized)
        return
    }
    // Process webhook...
}
Example
package main

import (
	"fmt"
	"log"

	"github.com/mqasimca/nylas-go"
)

func main() {
	client, _ := nylas.NewClient(nylas.WithAPIKey("your-api-key"))

	// In your webhook handler
	webhookSecret := "your-webhook-secret"
	signature := "signature-from-x-nylas-signature-header"
	body := []byte(`{"type": "message.created", "data": {...}}`)

	// Verify the webhook signature
	if !client.Webhooks.VerifySignature(webhookSecret, signature, body) {
		log.Fatal("Invalid webhook signature!")
	}

	fmt.Println("Webhook signature verified")
}

Directories

Path Synopsis
Package applications provides types for the Nylas Applications API.
Package applications provides types for the Nylas Applications API.
Package attachments provides types for working with email attachments in the Nylas API.
Package attachments provides types for working with email attachments in the Nylas API.
Package auth provides types and utilities for Nylas authentication operations.
Package auth provides types and utilities for Nylas authentication operations.
Package calendars provides types for working with calendars in the Nylas API.
Package calendars provides types for working with calendars in the Nylas API.
Package common provides shared types used across multiple Nylas API resources.
Package common provides shared types used across multiple Nylas API resources.
Package connectors provides types for the Nylas Connectors API.
Package connectors provides types for the Nylas Connectors API.
Package contacts provides types for working with contacts in the Nylas API.
Package contacts provides types for working with contacts in the Nylas API.
Package credentials provides types for the Nylas Credentials API.
Package credentials provides types for the Nylas Credentials API.
Package drafts provides types for working with email drafts in the Nylas API.
Package drafts provides types for working with email drafts in the Nylas API.
Package events provides types for working with calendar events in the Nylas API.
Package events provides types for working with calendar events in the Nylas API.
Package folders provides types for working with email folders/labels in the Nylas API.
Package folders provides types for working with email folders/labels in the Nylas API.
Package grants provides types for working with grants (connected accounts) in the Nylas API.
Package grants provides types for working with grants (connected accounts) in the Nylas API.
Package messages provides types for working with email messages in the Nylas API.
Package messages provides types for working with email messages in the Nylas API.
Package neural provides access to the Nylas Neural API for ML-powered email intelligence.
Package neural provides access to the Nylas Neural API for ML-powered email intelligence.
Package notetakers provides types for the Nylas Notetaker API.
Package notetakers provides types for the Nylas Notetaker API.
Package redirecturis provides types for the Nylas Redirect URIs API.
Package redirecturis provides types for the Nylas Redirect URIs API.
Package scheduler provides types for the Nylas Scheduler API.
Package scheduler provides types for the Nylas Scheduler API.
Package smartcompose provides types for the Nylas Smart Compose API.
Package smartcompose provides types for the Nylas Smart Compose API.
Package threads provides types for working with email threads in the Nylas API.
Package threads provides types for working with email threads in the Nylas API.
Package virtualcalendars provides access to Nylas Virtual Calendars.
Package virtualcalendars provides access to Nylas Virtual Calendars.
Package webhooks provides types for working with webhooks in the Nylas API.
Package webhooks provides types for working with webhooks in the Nylas API.

Jump to

Keyboard shortcuts

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