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)
}
}
}
Output:
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)
}
Output:
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)
}
}
}
Output:
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)
}
}
}
Output:
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))
}
Output:
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)
}
Output:
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)
}
Output:
Index ¶
- Variables
- func BatchDelete(ctx context.Context, grantID string, ids []string, ...) map[int]error
- func ExtractChallengeParameter(webhookURL string) (string, error)
- func IdempotencyKeyFromContext(ctx context.Context) (string, bool)
- func IsDebug(ctx context.Context) bool
- func Ptr[T any](v T) *T
- func RequestIDFromContext(ctx context.Context) (string, bool)
- func UserAgentFromContext(ctx context.Context) (string, bool)
- func WithDebug(ctx context.Context) context.Context
- func WithIdempotencyKey(ctx context.Context, key string) context.Context
- func WithOptions(parent context.Context, opts ContextOptions) context.Context
- func WithRequestID(ctx context.Context, requestID string) context.Context
- func WithUserAgent(ctx context.Context, userAgent string) context.Context
- type APIError
- type ApplicationsService
- type AttachmentsService
- type AuthService
- func (s *AuthService) AccessTokenInfo(ctx context.Context, accessToken string) (*auth.TokenInfoResponse, error)
- func (s *AuthService) CustomAuthentication(ctx context.Context, req *auth.CustomAuthRequest) (*grants.Grant, error)
- func (s *AuthService) DetectProvider(ctx context.Context, req *auth.ProviderDetectRequest) (*auth.ProviderDetectResponse, error)
- func (s *AuthService) ExchangeCodeForToken(ctx context.Context, req *auth.CodeExchangeRequest) (*auth.TokenExchangeResponse, error)
- func (s *AuthService) IDTokenInfo(ctx context.Context, idToken string) (*auth.TokenInfoResponse, error)
- func (s *AuthService) RefreshAccessToken(ctx context.Context, req *auth.RefreshTokenRequest) (*auth.TokenExchangeResponse, error)
- func (s *AuthService) Revoke(ctx context.Context, token string) error
- func (s *AuthService) URLForAdminConsent(config *auth.AdminConsentURLConfig) string
- func (s *AuthService) URLForOAuth2(config *auth.URLForAuthenticationConfig) string
- func (s *AuthService) URLForOAuth2PKCE(config *auth.PKCEURLConfig) string
- func (s *AuthService) ValidateAccessToken(ctx context.Context, accessToken string) (*auth.TokenInfoResponse, error)
- type BatchOperation
- type BatchResult
- func BatchCreate[T any, U any](ctx context.Context, grantID string, requests []U, ...) []BatchResult[T]
- func BatchGet[T any](ctx context.Context, grantID string, ids []string, ...) []BatchResult[T]
- func BatchUpdate[T any, U any](ctx context.Context, grantID string, updates []U, ...) []BatchResult[T]
- type CalendarsService
- func (s *CalendarsService) Availability(ctx context.Context, avail *calendars.AvailabilityRequest) (*calendars.AvailabilityResponse, error)
- func (s *CalendarsService) Create(ctx context.Context, grantID string, create *calendars.CreateRequest) (*calendars.Calendar, error)
- func (s *CalendarsService) Delete(ctx context.Context, grantID, calendarID string) error
- func (s *CalendarsService) FreeBusy(ctx context.Context, grantID string, freeBusy *calendars.FreeBusyRequest) ([]calendars.FreeBusyResponse, error)
- func (s *CalendarsService) Get(ctx context.Context, grantID, calendarID string) (*calendars.Calendar, error)
- func (s *CalendarsService) List(ctx context.Context, grantID string, opts *calendars.ListOptions) (*ListResponse[calendars.Calendar], error)
- func (s *CalendarsService) ListAll(ctx context.Context, grantID string, opts *calendars.ListOptions) *Iterator[calendars.Calendar]
- func (s *CalendarsService) ListAllResources(ctx context.Context, grantID string, opts *calendars.ListResourcesOptions) *Iterator[calendars.Resource]
- func (s *CalendarsService) ListResources(ctx context.Context, grantID string, opts *calendars.ListResourcesOptions) (*ListResponse[calendars.Resource], error)
- func (s *CalendarsService) Update(ctx context.Context, grantID, calendarID string, ...) (*calendars.Calendar, error)
- type CircuitBreakerConfig
- type CircuitBreakerCounts
- type CircuitBreakerState
- type Client
- func (c *Client) CircuitBreakerCounts() CircuitBreakerCounts
- func (c *Client) CircuitBreakerState() CircuitBreakerState
- func (c *Client) Do(req *http.Request, v any) (*Response[any], error)
- func (c *Client) DoList(req *http.Request, v any) (string, string, error)
- func (c *Client) DoRaw(req *http.Request, v any) error
- func (c *Client) NewMultipartRequest(ctx context.Context, method, path string, fields map[string]string, ...) (*http.Request, error)
- func (c *Client) NewRequest(ctx context.Context, method, path string, body any) (*http.Request, error)
- func (c *Client) OnRateLimit(observer RateLimitObserver)
- func (c *Client) RateLimits() Rate
- func (c *Client) SetRateLimitWarningThreshold(threshold float64)
- func (c *Client) Use(middleware ...Middleware)
- func (c *Client) WithLogger(logger Logger) *Client
- type ConflictError
- type ConnectorsService
- func (s *ConnectorsService) Create(ctx context.Context, create *connectors.CreateRequest) (*connectors.Connector, error)
- func (s *ConnectorsService) Delete(ctx context.Context, provider connectors.Provider) error
- func (s *ConnectorsService) Get(ctx context.Context, provider connectors.Provider) (*connectors.Connector, error)
- func (s *ConnectorsService) List(ctx context.Context, opts *connectors.ListOptions) (*ListResponse[connectors.Connector], error)
- func (s *ConnectorsService) ListAll(ctx context.Context, opts *connectors.ListOptions) *Iterator[connectors.Connector]
- func (s *ConnectorsService) Update(ctx context.Context, provider connectors.Provider, ...) (*connectors.Connector, error)
- type ContactsService
- func (s *ContactsService) Create(ctx context.Context, grantID string, create *contacts.CreateRequest) (*contacts.Contact, error)
- func (s *ContactsService) Delete(ctx context.Context, grantID, contactID string) error
- func (s *ContactsService) Get(ctx context.Context, grantID, contactID string) (*contacts.Contact, error)
- func (s *ContactsService) List(ctx context.Context, grantID string, opts *contacts.ListOptions) (*ListResponse[contacts.Contact], error)
- func (s *ContactsService) ListAll(ctx context.Context, grantID string, opts *contacts.ListOptions) *Iterator[contacts.Contact]
- func (s *ContactsService) ListGroups(ctx context.Context, grantID string) ([]contacts.Group, error)
- func (s *ContactsService) Update(ctx context.Context, grantID, contactID string, update *contacts.UpdateRequest) (*contacts.Contact, error)
- type ContextOptions
- type CredentialsService
- func (s *CredentialsService) Create(ctx context.Context, provider connectors.Provider, ...) (*credentials.Credential, error)
- func (s *CredentialsService) Delete(ctx context.Context, provider connectors.Provider, credentialID string) error
- func (s *CredentialsService) Get(ctx context.Context, provider connectors.Provider, credentialID string) (*credentials.Credential, error)
- func (s *CredentialsService) List(ctx context.Context, provider connectors.Provider, ...) (*ListResponse[credentials.Credential], error)
- func (s *CredentialsService) ListAll(ctx context.Context, provider connectors.Provider, ...) *Iterator[credentials.Credential]
- func (s *CredentialsService) Update(ctx context.Context, provider connectors.Provider, credentialID string, ...) (*credentials.Credential, error)
- type DraftsService
- func (s *DraftsService) Create(ctx context.Context, grantID string, create *drafts.CreateRequest) (*drafts.Draft, error)
- func (s *DraftsService) Delete(ctx context.Context, grantID, draftID string) error
- func (s *DraftsService) Get(ctx context.Context, grantID, draftID string) (*drafts.Draft, error)
- func (s *DraftsService) List(ctx context.Context, grantID string, opts *drafts.ListOptions) (*ListResponse[drafts.Draft], error)
- func (s *DraftsService) ListAll(ctx context.Context, grantID string, opts *drafts.ListOptions) *Iterator[drafts.Draft]
- func (s *DraftsService) Send(ctx context.Context, grantID, draftID string) (*drafts.Draft, error)
- func (s *DraftsService) Update(ctx context.Context, grantID, draftID string, update *drafts.UpdateRequest) (*drafts.Draft, error)
- type EventsService
- func (s *EventsService) Create(ctx context.Context, grantID, calendarID string, create *events.CreateRequest) (*events.Event, error)
- func (s *EventsService) Delete(ctx context.Context, grantID, eventID, calendarID string) error
- func (s *EventsService) Get(ctx context.Context, grantID, eventID string, calendarID string) (*events.Event, error)
- func (s *EventsService) Import(ctx context.Context, grantID string, opts *events.ImportOptions) (*ListResponse[events.Event], error)
- func (s *EventsService) ImportAll(ctx context.Context, grantID string, opts *events.ImportOptions) *Iterator[events.Event]
- func (s *EventsService) List(ctx context.Context, grantID string, opts *events.ListOptions) (*ListResponse[events.Event], error)
- func (s *EventsService) ListAll(ctx context.Context, grantID string, opts *events.ListOptions) *Iterator[events.Event]
- func (s *EventsService) SendRSVP(ctx context.Context, grantID, eventID, calendarID string, ...) error
- func (s *EventsService) Update(ctx context.Context, grantID, eventID, calendarID string, ...) (*events.Event, error)
- type FoldersService
- func (s *FoldersService) Create(ctx context.Context, grantID string, create *folders.CreateRequest) (*folders.Folder, error)
- func (s *FoldersService) Delete(ctx context.Context, grantID, folderID string) error
- func (s *FoldersService) Get(ctx context.Context, grantID, folderID string) (*folders.Folder, error)
- func (s *FoldersService) List(ctx context.Context, grantID string, opts *folders.ListOptions) (*ListResponse[folders.Folder], error)
- func (s *FoldersService) ListAll(ctx context.Context, grantID string, opts *folders.ListOptions) *Iterator[folders.Folder]
- func (s *FoldersService) Update(ctx context.Context, grantID, folderID string, update *folders.UpdateRequest) (*folders.Folder, error)
- type GrantsService
- func (s *GrantsService) Delete(ctx context.Context, grantID string) error
- func (s *GrantsService) Get(ctx context.Context, grantID string) (*grants.Grant, error)
- func (s *GrantsService) List(ctx context.Context, opts *grants.ListOptions) (*ListResponse[grants.Grant], error)
- func (s *GrantsService) ListAll(ctx context.Context, opts *grants.ListOptions) *Iterator[grants.Grant]
- func (s *GrantsService) Update(ctx context.Context, grantID string, update *grants.UpdateRequest) (*grants.Grant, error)
- type HTTPTransportConfig
- type Iterator
- type ListResponse
- type LogLevel
- type Logger
- type MessagesService
- func (s *MessagesService) Clean(ctx context.Context, grantID string, clean *messages.CleanRequest) ([]messages.CleanResponse, error)
- func (s *MessagesService) Delete(ctx context.Context, grantID, messageID string) error
- func (s *MessagesService) Get(ctx context.Context, grantID, messageID string) (*messages.Message, error)
- func (s *MessagesService) GetScheduled(ctx context.Context, grantID, scheduleID string) (*messages.ScheduledMessage, error)
- func (s *MessagesService) List(ctx context.Context, grantID string, opts *messages.ListOptions) (*ListResponse[messages.Message], error)
- func (s *MessagesService) ListAll(ctx context.Context, grantID string, opts *messages.ListOptions) *Iterator[messages.Message]
- func (s *MessagesService) ListScheduled(ctx context.Context, grantID string) (messages.ScheduledMessagesList, error)
- func (s *MessagesService) Send(ctx context.Context, grantID string, send *messages.SendRequest) (*messages.Message, error)
- func (s *MessagesService) StopScheduled(ctx context.Context, grantID, scheduleID string) error
- func (s *MessagesService) Update(ctx context.Context, grantID, messageID string, update *messages.UpdateRequest) (*messages.Message, error)
- type Middleware
- func HeaderMiddleware(headers map[string]string) Middleware
- func MetricsMiddleware(onRequest func(method, path string, duration int64, statusCode int, err error)) Middleware
- func RequestIDMiddleware(generateID func() string) Middleware
- func RetryMiddleware(maxRetries int, shouldRetry func(*http.Response, error) bool) Middleware
- type NeuralService
- func (s *NeuralService) Categorize(ctx context.Context, grantID, messageID string) (*neural.CategorizeResponse, error)
- func (s *NeuralService) CategorizeBatch(ctx context.Context, grantID string, messageIDs []string) ([]*neural.CategorizeResponse, error)
- func (s *NeuralService) CleanConversation(ctx context.Context, grantID, messageID string, ...) (*neural.CleanConversationResponse, error)
- func (s *NeuralService) ExtractSignature(ctx context.Context, grantID, messageID string, ...) (*neural.SignatureExtractionResponse, error)
- func (s *NeuralService) ExtractText(ctx context.Context, grantID, messageID string, opts *neural.OCRRequest) (*neural.OCRResponse, error)
- type NoopLogger
- type NotetakersService
- func (s *NotetakersService) Cancel(ctx context.Context, grantID, notetakerID string) error
- func (s *NotetakersService) Create(ctx context.Context, grantID string, createReq *notetakers.CreateRequest) (*notetakers.Notetaker, error)
- func (s *NotetakersService) Get(ctx context.Context, grantID, notetakerID string) (*notetakers.Notetaker, error)
- func (s *NotetakersService) GetHistory(ctx context.Context, grantID, notetakerID string) (*notetakers.History, error)
- func (s *NotetakersService) GetMedia(ctx context.Context, grantID, notetakerID string) ([]notetakers.Media, error)
- func (s *NotetakersService) Leave(ctx context.Context, grantID, notetakerID string) error
- func (s *NotetakersService) List(ctx context.Context, grantID string, opts *notetakers.ListOptions) (*ListResponse[notetakers.Notetaker], error)
- func (s *NotetakersService) ListAll(ctx context.Context, grantID string, opts *notetakers.ListOptions) *Iterator[notetakers.Notetaker]
- type Option
- func WithAPIKey(key string) Option
- func WithBaseURL(baseURL string) Option
- func WithCircuitBreaker(config CircuitBreakerConfig) Option
- func WithDisableJitter(disable bool) Option
- func WithHTTPClient(hc *http.Client) Option
- func WithHTTPTransport(config HTTPTransportConfig) Option
- func WithMaxRetries(n int) Option
- func WithMaxRetryWait(d time.Duration) Option
- func WithRateLimitWarningThreshold(threshold float64) Option
- func WithRegion(region Region) Option
- func WithRetryWait(d time.Duration) Option
- func WithTimeout(d time.Duration) Option
- type QueryBuilder
- func (q *QueryBuilder) Add(key, value string) *QueryBuilder
- func (q *QueryBuilder) After(timestamp int64) *QueryBuilder
- func (q *QueryBuilder) Before(timestamp int64) *QueryBuilder
- func (q *QueryBuilder) CalendarID(id string) *QueryBuilder
- func (q *QueryBuilder) Clone() *QueryBuilder
- func (q *QueryBuilder) Del(key string) *QueryBuilder
- func (q *QueryBuilder) Encode() string
- func (q *QueryBuilder) EndTime(timestamp int64) *QueryBuilder
- func (q *QueryBuilder) From(email string) *QueryBuilder
- func (q *QueryBuilder) Get(key string) string
- func (q *QueryBuilder) Has(key string) bool
- func (q *QueryBuilder) HasAttachment(has bool) *QueryBuilder
- func (q *QueryBuilder) In(key string, values []string) *QueryBuilder
- func (q *QueryBuilder) Limit(limit int) *QueryBuilder
- func (q *QueryBuilder) Metadata(key, value string) *QueryBuilder
- func (q *QueryBuilder) OrderBy(field string, desc bool) *QueryBuilder
- func (q *QueryBuilder) PageToken(token string) *QueryBuilder
- func (q *QueryBuilder) Reset() *QueryBuilder
- func (q *QueryBuilder) SearchQuery(query string) *QueryBuilder
- func (q *QueryBuilder) Select(fields ...string) *QueryBuilder
- func (q *QueryBuilder) Set(key, value string) *QueryBuilder
- func (q *QueryBuilder) Starred(starred bool) *QueryBuilder
- func (q *QueryBuilder) StartTime(timestamp int64) *QueryBuilder
- func (q *QueryBuilder) Subject(subject string) *QueryBuilder
- func (q *QueryBuilder) To(email string) *QueryBuilder
- func (q *QueryBuilder) Unread(unread bool) *QueryBuilder
- func (q *QueryBuilder) Values() url.Values
- type QueryValues
- type QuotaExceededError
- type Rate
- type RateLimitError
- type RateLimitObserver
- type RedirectURIsService
- func (s *RedirectURIsService) Create(ctx context.Context, create *redirecturis.CreateRequest) (*redirecturis.RedirectURI, error)
- func (s *RedirectURIsService) Delete(ctx context.Context, redirectURIID string) error
- func (s *RedirectURIsService) Get(ctx context.Context, redirectURIID string) (*redirecturis.RedirectURI, error)
- func (s *RedirectURIsService) List(ctx context.Context, opts *redirecturis.ListOptions) (*ListResponse[redirecturis.RedirectURI], error)
- func (s *RedirectURIsService) ListAll(ctx context.Context, opts *redirecturis.ListOptions) *Iterator[redirecturis.RedirectURI]
- func (s *RedirectURIsService) Update(ctx context.Context, redirectURIID string, update *redirecturis.UpdateRequest) (*redirecturis.RedirectURI, error)
- type Region
- type Response
- type RoundTripperFunc
- type SchedulerService
- func (s *SchedulerService) CancelBooking(ctx context.Context, configID, bookingID, reason string) error
- func (s *SchedulerService) ConfirmBooking(ctx context.Context, configID, bookingID string, ...) (*scheduler.Booking, error)
- func (s *SchedulerService) CreateBooking(ctx context.Context, configID string, bookingReq *scheduler.BookingRequest) (*scheduler.Booking, error)
- func (s *SchedulerService) CreateConfiguration(ctx context.Context, grantID string, configReq *scheduler.ConfigurationRequest) (*scheduler.Configuration, error)
- func (s *SchedulerService) CreateSession(ctx context.Context, sessionReq *scheduler.SessionRequest) (*scheduler.Session, error)
- func (s *SchedulerService) DeleteConfiguration(ctx context.Context, grantID, configID string) error
- func (s *SchedulerService) DeleteSession(ctx context.Context, sessionID string) error
- func (s *SchedulerService) GetAvailability(ctx context.Context, req *scheduler.AvailabilityRequest) (*scheduler.AvailabilityResponse, error)
- func (s *SchedulerService) GetBooking(ctx context.Context, configID, bookingID string) (*scheduler.Booking, error)
- func (s *SchedulerService) GetConfiguration(ctx context.Context, grantID, configID string) (*scheduler.Configuration, error)
- func (s *SchedulerService) ListBookings(ctx context.Context, configID string, opts *scheduler.ListBookingsOptions) (*ListResponse[scheduler.Booking], error)
- func (s *SchedulerService) ListConfigurations(ctx context.Context, grantID string, opts *scheduler.ListConfigurationsOptions) (*ListResponse[scheduler.Configuration], error)
- func (s *SchedulerService) RescheduleBooking(ctx context.Context, configID, bookingID string, ...) (*scheduler.Booking, error)
- func (s *SchedulerService) UpdateConfiguration(ctx context.Context, grantID, configID string, ...) (*scheduler.Configuration, error)
- type SmartComposeService
- type StdLogger
- func (l *StdLogger) Debug(ctx context.Context, msg string, fields ...any)
- func (l *StdLogger) Error(ctx context.Context, msg string, fields ...any)
- func (l *StdLogger) Info(ctx context.Context, msg string, fields ...any)
- func (l *StdLogger) SetLevel(level LogLevel)
- func (l *StdLogger) Warn(ctx context.Context, msg string, fields ...any)
- type StructuredLogger
- func (l *StructuredLogger) Debug(ctx context.Context, msg string, fields ...any)
- func (l *StructuredLogger) Error(ctx context.Context, msg string, fields ...any)
- func (l *StructuredLogger) Info(ctx context.Context, msg string, fields ...any)
- func (l *StructuredLogger) Warn(ctx context.Context, msg string, fields ...any)
- type ThreadsService
- func (s *ThreadsService) Delete(ctx context.Context, grantID, threadID string) error
- func (s *ThreadsService) Get(ctx context.Context, grantID, threadID string) (*threads.Thread, error)
- func (s *ThreadsService) List(ctx context.Context, grantID string, opts *threads.ListOptions) (*ListResponse[threads.Thread], error)
- func (s *ThreadsService) ListAll(ctx context.Context, grantID string, opts *threads.ListOptions) *Iterator[threads.Thread]
- func (s *ThreadsService) Update(ctx context.Context, grantID, threadID string, update *threads.UpdateRequest) (*threads.Thread, error)
- type ValidationError
- type VirtualCalendarsService
- func (s *VirtualCalendarsService) Create(ctx context.Context, grantID string, create *virtualcalendars.CreateRequest) (*virtualcalendars.VirtualCalendar, error)
- func (s *VirtualCalendarsService) Delete(ctx context.Context, grantID, calendarID string) error
- func (s *VirtualCalendarsService) Get(ctx context.Context, grantID, calendarID string) (*virtualcalendars.VirtualCalendar, error)
- func (s *VirtualCalendarsService) List(ctx context.Context, grantID string, opts *virtualcalendars.ListOptions) (*ListResponse[virtualcalendars.VirtualCalendar], error)
- func (s *VirtualCalendarsService) ListAll(ctx context.Context, grantID string, opts *virtualcalendars.ListOptions) *Iterator[virtualcalendars.VirtualCalendar]
- func (s *VirtualCalendarsService) Update(ctx context.Context, grantID, calendarID string, ...) (*virtualcalendars.VirtualCalendar, error)
- type WebhooksService
- func (s *WebhooksService) Create(ctx context.Context, create *webhooks.CreateRequest) (*webhooks.Webhook, error)
- func (s *WebhooksService) Delete(ctx context.Context, webhookID string) error
- func (s *WebhooksService) Get(ctx context.Context, webhookID string) (*webhooks.Webhook, error)
- func (s *WebhooksService) GetIPAddresses(ctx context.Context) (*webhooks.IPAddressesResponse, error)
- func (s *WebhooksService) List(ctx context.Context, opts *webhooks.ListOptions) (*ListResponse[webhooks.Webhook], error)
- func (s *WebhooksService) ListAll(ctx context.Context, opts *webhooks.ListOptions) *Iterator[webhooks.Webhook]
- func (s *WebhooksService) ParseWebhookEvent(body []byte, secret, signature string) (*webhooks.WebhookEvent, error)
- func (s *WebhooksService) RotateSecret(ctx context.Context, webhookID string) (*webhooks.RotateSecretResponse, error)
- func (s *WebhooksService) Update(ctx context.Context, webhookID string, update *webhooks.UpdateRequest) (*webhooks.Webhook, error)
- func (s *WebhooksService) VerifySignature(secret, signature string, body []byte) bool
Examples ¶
- Package (AdvancedRetry)
- Package (CompleteWorkflow)
- Package (ConcurrentRequests)
- Package (ErrorHandling)
- Package (Pagination)
- Package (RateLimitMonitoring)
- Package (RateLimits)
- CalendarsService.Availability
- EventsService.Create
- Iterator
- Iterator.Collect
- MessagesService.List
- MessagesService.Send
- MessagesService.Send (WithAttachment)
- NewClient
- NewClient (WithOptions)
- SchedulerService.GetAvailability
- WebhooksService.ParseWebhookEvent
- WebhooksService.VerifySignature
Constants ¶
This section is empty.
Variables ¶
var ( ErrMissingAPIKey = errors.New("nylas: API key required (use WithAPIKey)") 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
}
var ( // Additional sentinel errors ErrConflict = errors.New("nylas: resource conflict") ErrValidation = errors.New("nylas: validation error") )
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
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
IdempotencyKeyFromContext retrieves the idempotency key from the context.
func RequestIDFromContext ¶ added in v0.1.4
RequestIDFromContext retrieves the request ID from the context.
func UserAgentFromContext ¶ added in v0.1.4
UserAgentFromContext retrieves the custom user agent from the context.
func WithDebug ¶ added in v0.1.4
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
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
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
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.
type ApplicationsService ¶ added in v0.1.3
type ApplicationsService service
ApplicationsService handles application configuration operations.
func (*ApplicationsService) GetDetails ¶ added in v0.1.3
func (s *ApplicationsService) GetDetails(ctx context.Context) (*applications.ApplicationDetails, error)
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
func (s *AuthService) DetectProvider(ctx context.Context, req *auth.ProviderDetectRequest) (*auth.ProviderDetectResponse, error)
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.
type BatchResult ¶ added in v0.1.4
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
func (s *CalendarsService) Availability(ctx context.Context, avail *calendars.AvailabilityRequest) (*calendars.AvailabilityResponse, error)
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)
}
}
Output:
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
func (s *CalendarsService) FreeBusy(ctx context.Context, grantID string, freeBusy *calendars.FreeBusyRequest) ([]calendars.FreeBusyResponse, error)
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
func (s *CalendarsService) List(ctx context.Context, grantID string, opts *calendars.ListOptions) (*ListResponse[calendars.Calendar], error)
List returns calendars for a grant.
func (*CalendarsService) ListAll ¶ added in v0.1.2
func (s *CalendarsService) ListAll(ctx context.Context, grantID string, opts *calendars.ListOptions) *Iterator[calendars.Calendar]
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
func (s *CalendarsService) ListResources(ctx context.Context, grantID string, opts *calendars.ListResourcesOptions) (*ListResponse[calendars.Resource], error)
ListResources returns room resources available for booking (conference rooms, equipment, etc.).
Note: Room resources availability depends on the calendar provider (Google Workspace, Microsoft 365).
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 ¶
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
}
Output:
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
}
Output:
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 ¶
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) DoRaw ¶
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 ¶
RateLimits returns the current rate limit information from the last API response.
func (*Client) SetRateLimitWarningThreshold ¶ added in v0.1.4
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
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
func (s *ConnectorsService) Create(ctx context.Context, create *connectors.CreateRequest) (*connectors.Connector, error)
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
func (s *ConnectorsService) Get(ctx context.Context, provider connectors.Provider) (*connectors.Connector, error)
Get returns a single connector by provider.
func (*ConnectorsService) List ¶ added in v0.1.3
func (s *ConnectorsService) List(ctx context.Context, opts *connectors.ListOptions) (*ListResponse[connectors.Connector], error)
List returns all connectors.
func (*ConnectorsService) ListAll ¶ added in v0.1.3
func (s *ConnectorsService) ListAll(ctx context.Context, opts *connectors.ListOptions) *Iterator[connectors.Connector]
ListAll returns an iterator for all connectors.
func (*ConnectorsService) Update ¶ added in v0.1.3
func (s *ConnectorsService) Update(ctx context.Context, provider connectors.Provider, update *connectors.UpdateRequest) (*connectors.Connector, error)
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
func (s *ContactsService) List(ctx context.Context, grantID string, opts *contacts.ListOptions) (*ListResponse[contacts.Contact], error)
List returns contacts for a grant.
func (*ContactsService) ListAll ¶ added in v0.1.2
func (s *ContactsService) ListAll(ctx context.Context, grantID string, opts *contacts.ListOptions) *Iterator[contacts.Contact]
ListAll returns an iterator for all contacts.
func (*ContactsService) ListGroups ¶ added in v0.1.2
ListGroups returns contact groups for a grant.
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
func (s *CredentialsService) Create(ctx context.Context, provider connectors.Provider, create *credentials.CreateRequest) (*credentials.Credential, error)
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
func (s *CredentialsService) List(ctx context.Context, provider connectors.Provider, opts *credentials.ListOptions) (*ListResponse[credentials.Credential], error)
List returns all credentials for a provider.
func (*CredentialsService) ListAll ¶ added in v0.1.3
func (s *CredentialsService) ListAll(ctx context.Context, provider connectors.Provider, opts *credentials.ListOptions) *Iterator[credentials.Credential]
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) 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.
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)
}
Output:
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
func (s *FoldersService) List(ctx context.Context, grantID string, opts *folders.ListOptions) (*ListResponse[folders.Folder], error)
List returns folders for a grant.
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) List ¶ added in v0.1.2
func (s *GrantsService) List(ctx context.Context, opts *grants.ListOptions) (*ListResponse[grants.Grant], error)
List returns all grants.
func (*GrantsService) ListAll ¶ added in v0.1.3
func (s *GrantsService) ListAll(ctx context.Context, opts *grants.ListOptions) *Iterator[grants.Grant]
ListAll returns an iterator for all grants using offset-based pagination.
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)
}
}
Output:
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 ¶
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))
}
Output:
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 ¶
func (s *MessagesService) Clean(ctx context.Context, grantID string, clean *messages.CleanRequest) ([]messages.CleanResponse, error)
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 ¶
func (s *MessagesService) List(ctx context.Context, grantID string, opts *messages.ListOptions) (*ListResponse[messages.Message], error)
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)
}
}
Output:
func (*MessagesService) ListAll ¶
func (s *MessagesService) ListAll(ctx context.Context, grantID string, opts *messages.ListOptions) *Iterator[messages.Message]
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)
}
Output:
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)
}
Output:
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
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)
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
func (s *NotetakersService) List(ctx context.Context, grantID string, opts *notetakers.ListOptions) (*ListResponse[notetakers.Notetaker], error)
List returns all notetakers for a grant.
func (*NotetakersService) ListAll ¶ added in v0.1.3
func (s *NotetakersService) ListAll(ctx context.Context, grantID string, opts *notetakers.ListOptions) *Iterator[notetakers.Notetaker]
ListAll returns an iterator for all notetakers.
type Option ¶
type Option func(*Client)
Option is a functional option for configuring the Client.
func WithAPIKey ¶
WithAPIKey sets the API key for authentication.
func WithBaseURL ¶
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
WithDisableJitter disables jitter in retry backoff calculations. By default, jitter is enabled to avoid thundering herd problems.
func WithHTTPClient ¶
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 ¶
WithMaxRetries sets the maximum number of retry attempts for failed requests.
func WithMaxRetryWait ¶ added in v0.1.4
WithMaxRetryWait sets the maximum wait time for retries (caps exponential backoff).
func WithRateLimitWarningThreshold ¶ added in v0.1.4
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 WithRetryWait ¶
WithRetryWait sets the base wait time between retries (uses exponential backoff).
func WithTimeout ¶
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 ¶
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
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 ¶
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
func (s *RedirectURIsService) Create(ctx context.Context, create *redirecturis.CreateRequest) (*redirecturis.RedirectURI, error)
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
func (s *RedirectURIsService) List(ctx context.Context, opts *redirecturis.ListOptions) (*ListResponse[redirecturis.RedirectURI], error)
List returns all redirect URIs for the application.
func (*RedirectURIsService) ListAll ¶ added in v0.1.3
func (s *RedirectURIsService) ListAll(ctx context.Context, opts *redirecturis.ListOptions) *Iterator[redirecturis.RedirectURI]
ListAll returns an iterator for all redirect URIs.
func (*RedirectURIsService) Update ¶ added in v0.1.3
func (s *RedirectURIsService) Update(ctx context.Context, redirectURIID string, update *redirecturis.UpdateRequest) (*redirecturis.RedirectURI, error)
Update updates a redirect URI.
type RoundTripperFunc ¶ added in v0.1.4
RoundTripperFunc is an adapter to allow the use of ordinary functions as http.RoundTrippers.
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
func (s *SchedulerService) GetAvailability(ctx context.Context, req *scheduler.AvailabilityRequest) (*scheduler.AvailabilityResponse, error)
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)
}
}
Output:
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
func (s *SchedulerService) ListBookings(ctx context.Context, configID string, opts *scheduler.ListBookingsOptions) (*ListResponse[scheduler.Booking], error)
ListBookings returns all bookings for a configuration.
func (*SchedulerService) ListConfigurations ¶ added in v0.1.3
func (s *SchedulerService) ListConfigurations(ctx context.Context, grantID string, opts *scheduler.ListConfigurationsOptions) (*ListResponse[scheduler.Configuration], error)
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
func (s *SmartComposeService) ComposeMessage(ctx context.Context, grantID string, compose *smartcompose.ComposeRequest) (*smartcompose.ComposeResponse, error)
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
NewStdLogger creates a standard logger with the specified log level.
Example:
logger := nylas.NewStdLogger(nylas.LogLevelDebug) client.SetLogger(logger)
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)
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 ¶
func (s *ThreadsService) List(ctx context.Context, grantID string, opts *threads.ListOptions) (*ListResponse[threads.Thread], error)
List returns threads for a grant.
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
func (s *VirtualCalendarsService) Create(ctx context.Context, grantID string, create *virtualcalendars.CreateRequest) (*virtualcalendars.VirtualCalendar, error)
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
func (s *VirtualCalendarsService) Get(ctx context.Context, grantID, calendarID string) (*virtualcalendars.VirtualCalendar, error)
Get retrieves a virtual calendar by ID.
func (*VirtualCalendarsService) List ¶ added in v0.1.4
func (s *VirtualCalendarsService) List(ctx context.Context, grantID string, opts *virtualcalendars.ListOptions) (*ListResponse[virtualcalendars.VirtualCalendar], error)
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
func (s *VirtualCalendarsService) ListAll(ctx context.Context, grantID string, opts *virtualcalendars.ListOptions) *Iterator[virtualcalendars.VirtualCalendar]
ListAll returns an iterator for all virtual calendars.
func (*VirtualCalendarsService) Update ¶ added in v0.1.4
func (s *VirtualCalendarsService) Update(ctx context.Context, grantID, calendarID string, update *virtualcalendars.UpdateRequest) (*virtualcalendars.VirtualCalendar, error)
Update updates a virtual calendar.
type WebhooksService ¶
type WebhooksService service
WebhooksService handles operations on webhook subscriptions.
func (*WebhooksService) Create ¶ added in v0.1.2
func (s *WebhooksService) Create(ctx context.Context, create *webhooks.CreateRequest) (*webhooks.Webhook, error)
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) 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
func (s *WebhooksService) List(ctx context.Context, opts *webhooks.ListOptions) (*ListResponse[webhooks.Webhook], error)
List returns all webhooks.
func (*WebhooksService) ListAll ¶ added in v0.1.3
func (s *WebhooksService) ListAll(ctx context.Context, opts *webhooks.ListOptions) *Iterator[webhooks.Webhook]
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)
}
Output:
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")
}
Output:
Source Files
¶
- applications.go
- attachments.go
- auth.go
- batch.go
- calendars.go
- circuitbreaker.go
- connectors.go
- contacts.go
- context.go
- credentials.go
- doc.go
- drafts.go
- errors.go
- events.go
- folders.go
- grants.go
- helpers.go
- iterator.go
- logger.go
- messages.go
- middleware.go
- neural.go
- notetakers.go
- nylas.go
- options.go
- ptr.go
- query.go
- rate.go
- redirecturis.go
- response.go
- scheduler.go
- smartcompose.go
- threads.go
- virtualcalendars.go
- webhooks.go
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. |