> ## Documentation Index
> Fetch the complete documentation index at: https://developers.sendlayer.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Golang SDK

> Learn how to install and use the SendLayer Go SDK.

## Prerequisites

Before getting started, you'll need to:

1. Authorize your [sending domain](https://sendlayer.com/docs/authorizing-your-domain/)
2. Create and retrieve your [SendLayer API key](https://sendlayer.com/docs/managing-api-keys/)

## Installation

Install the SendLayer Go SDK using the `go get` command:

```bash theme={null}
go get github.com/sendlayer/sendlayer-go
```

## Usage

After installation, you can use the SDK modules for sending emails, managing webhooks, and retrieving email events.

### Send Email in Golang

Initialize the client and call `sl.Emails.Send()` with a `SendEmailRequest`.

```go sendEmail.go theme={null}
package main

import (
	"fmt"
	"log"

	"github.com/sendlayer/sendlayer-go"
)

func main() {
	// Initialize the client with your API key
	sl := sendlayer.New("your-api-key")

	// Send an email
	resp, err := sl.Emails.Send(&sendlayer.SendEmailRequest{
		From:    "sender@example.com",
		To:      "recipient@example.com",
		Subject: "Test Email",
		Text:    "This is a test email",
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Email sent! Message ID:", resp.MessageID)
}
```

#### Send HTML Emails in Go

To send HTML emails, set the `Html` field in the request payload.

```go sendEmail.go theme={null}
package main

import (
	"fmt"
	"log"

	"github.com/sendlayer/sendlayer-go"
)

func main() {
	sl := sendlayer.New("your-api-key")

	// Send an HTML email
	resp, err := sl.Emails.Send(&sendlayer.SendEmailRequest{
		From:    "sender@example.com",
		To:      "recipient@example.com",
		Subject: "Test Email",
		Text:    "Plain text fallback",
		Html:    "<html><body><p>This is a test email sent with the <a href=\"https://sendlayer.com\">SendLayer</a> API!</p></body></html>",
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Email sent! Message ID:", resp.MessageID)
}
```

<Note>You can include both `Text` and `Html` to send plain text and HTML versions of the same email.</Note>

#### Send Email to Multiple Recipients

Use `EmailAddress` objects to send to multiple recipients, including `Cc`, `Bcc`, and `ReplyTo`.

```go sendEmail.go theme={null}
package main

import (
	"fmt"
	"log"

	"github.com/sendlayer/sendlayer-go"
)

func main() {
	sl := sendlayer.New("your-api-key")

	// Send to multiple recipients
	resp, err := sl.Emails.Send(&sendlayer.SendEmailRequest{
		From: sendlayer.EmailAddress{
			Email: "sender@example.com",
			Name:  "Sender Name",
		},
		To: []sendlayer.EmailAddress{
			{Email: "recipient1@example.com", Name: "Recipient 1"},
			{Email: "recipient2@example.com", Name: "Recipient 2"},
		},
		Subject: "Complex Email",
		Text:    "This is a test email!",
		Html:    "<p>This is a <strong>test email</strong>!</p>",
		Cc:      []sendlayer.EmailAddress{{Email: "cc@example.com", Name: "CC Recipient"}},
		Bcc:     []sendlayer.EmailAddress{{Email: "bcc@example.com", Name: "BCC Recipient"}},
		ReplyTo: sendlayer.EmailAddress{Email: "reply@example.com", Name: "Reply To"},
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Email sent! Message ID:", resp.MessageID)
}
```

`From` and `To` accept either a string email or `EmailAddress` values. `Cc`, `Bcc`, and `ReplyTo` support the same flexible format.

<Note>There are limits to the number of email recipients you can add to a single request. See our [rate limiting](/api-reference/rate-limit) guide to learn more.</Note>

#### Include Attachments in Email

Include attachments by setting the `Attachments` field in `SendEmailRequest`.

```go sendEmail.go theme={null}
package main

import (
	"fmt"
	"log"

	"github.com/sendlayer/sendlayer-go"
)

func main() {
	sl := sendlayer.New("your-api-key")

	// Send email with attachments
	resp, err := sl.Emails.Send(&sendlayer.SendEmailRequest{
		From: sendlayer.EmailAddress{Email: "sender@example.com", Name: "Sender Name"},
		To: []sendlayer.EmailAddress{
			{Email: "recipient1@example.com", Name: "Recipient"},
		},
		Subject: "Complex Email",
		Text:    "Plain text fallback",
		Html:    "<p>This is a <strong>test email</strong>!</p>",
		Attachments: []sendlayer.Attachment{
			{Path: "path/to/file.pdf", Type: "application/pdf"},
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Email sent! Message ID:", resp.MessageID)
}
```

<Warning>The maximum email size SendLayer allows is 10MB. This includes both the message as well as attachment files.</Warning>

Set `Path` to your local file path or hosted file URL, then set the file `Type` (MIME type).

SendLayer SDK supports both local and remote file attachments and allows you to add multiple attachment files. See our tutorial to learn more about [attaching files to emails](/guides/send-email-with-attachments).

#### Email Request Parameters

The table below contains the supported fields in `SendEmailRequest`.

| Field         | Type                                          | Required | Description                                                                         |
| ------------- | --------------------------------------------- | -------- | ----------------------------------------------------------------------------------- |
| `From`        | `string` or `EmailAddress`                    | Yes      | Sender email, as a plain email string or `EmailAddress` (`Email` + optional `Name`) |
| `To`          | `string`, `EmailAddress`, or `[]EmailAddress` | Yes      | Recipient email(s), as one address or multiple addresses                            |
| `Subject`     | `string`                                      | Yes      | Email subject line                                                                  |
| `Text`        | `string`                                      | Yes      | Plain text body                                                                     |
| `Html`        | `string`                                      | No       | HTML body                                                                           |
| `Cc`          | `EmailAddress` or `[]EmailAddress`            | No       | Carbon-copy recipients                                                              |
| `Bcc`         | `EmailAddress` or `[]EmailAddress`            | No       | Blind carbon-copy recipients                                                        |
| `ReplyTo`     | `EmailAddress` or `[]EmailAddress`            | No       | Reply-to recipient(s)                                                               |
| `Attachments` | `[]Attachment`                                | No       | File attachments with `Path` and MIME `Type`                                        |
| `Headers`     | `map[string]string`                           | No       | Custom email headers                                                                |
| `Tags`        | `[]string`                                    | No       | Tags for categorizing emails                                                        |

### Manage Webhooks in Go

With the SendLayer Go SDK, you can create, list, and delete webhooks.

#### Create a New Webhook

Call `Webhooks.Create()` with a `WebhookCreateRequest`.

```go webhooks.go theme={null}
package main

import (
	"fmt"
	"log"

	"github.com/sendlayer/sendlayer-go"
)

func main() {
	sl := sendlayer.New("your-api-key")

	// Create a webhook
	webhook, err := sl.Webhooks.Create(&sendlayer.WebhookCreateRequest{
		WebhookURL: "https://your-domain.com/webhook",
		Event:      "open",
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Webhook created! ID:", webhook.WebhookID)
}
```

The `Event` field accepts the following options:

* bounce
* click
* open
* unsubscribe
* complaint
* delivery

Example success response for new webhook:

```json theme={null}
{
   "NewWebhookID": 23718
}
```

#### Get All Webhooks

To view all the webhooks you've created, use the `Webhooks.Get()` method.

```go webhooks.go theme={null}
package main

import (
	"fmt"
	"log"

	"github.com/sendlayer/sendlayer-go"
)

func main() {
	sl := sendlayer.New("your-api-key")

	// Get all webhooks
	webhooks, err := sl.Webhooks.Get()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Webhooks:", webhooks)
}
```

Here is an example response:

```json theme={null}
{
  "Webhooks": [
    {
      "WebhookID": "23718",
      "CreatedAt": "2025-04-11 09:43:07",
      "UpdatedAt": "2025-04-11 09:43:07", 
      "Status": "Enabled",
      "WebhookURL": "http://example.com/webhook",
      "Event": "delivered",
      "LastResponseCode": "0",
      "LastResponseBody": "",
      "LastResponseAt": "0000-00-00 00:00:00",
      "LastResponseTryCounter": "0"
    }
  ]
}
```

#### Delete a Webhook

To delete a specific webhook, pass the webhook ID to `Webhooks.Delete()`.

<Warning>Deleting a webhook cannot be undone.</Warning>

```go webhooks.go theme={null}
package main

import (
	"fmt"
	"log"

	"github.com/sendlayer/sendlayer-go"
)

func main() {
	sl := sendlayer.New("your-api-key")

	// Delete a webhook
	webhookId := 23718
	err := sl.Webhooks.Delete(webhookId)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Webhook deleted successfully")
}
```

#### Webhook Request Parameters

The table below contains the supported inputs in the `Webhooks` module.

| Parameter    | Type     | Required     | Description                                       |
| ------------ | -------- | ------------ | ------------------------------------------------- |
| `WebhookURL` | `string` | Yes (create) | Webhook endpoint URL where SendLayer sends events |
| `Event`      | `string` | Yes (create) | Event type for the webhook subscription           |
| `webhookId`  | `int`    | Yes (delete) | Unique webhook ID to delete                       |

### Retrieve Email Events

Use the `Events` module to retrieve email delivery and engagement events.

#### Get All Events

Initialize the client and call `Events.Get(nil)` to retrieve recent events.

```go events.go theme={null}
package main

import (
	"fmt"
	"log"

	"github.com/sendlayer/sendlayer-go"
)

func main() {
	sl := sendlayer.New("your-api-key")

	// Get all events
	events, err := sl.Events.Get(nil)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Total events:", events.TotalRecords)
}
```

Example response:

```json theme={null}
{
  "totalRecords": 5,
  "events": [
    {
      "Event": "delivered",
      "LoggedAt": 1746340896,
      "LogLevel": "info",
      "Message": {
        "Headers": {
          "MessageId": "06e4491f-fc5a-49cb-bc57-xxxxxx",
          "From": [["", "sender@example.com"]],
          "ReplyTo": [],
          "To": [["", "recipient@example.com"]],
          "Cc": [],
          "Bcc": []
        },
        "Size": 2004,
        "Transport": "api"
      },
      "Recipient": "recipient@example.com",
      "Reason": "Email has been delivered."
    }
  ]
}
```

#### Filter Events

Pass a `GetEventsRequest` to filter by date range and event type.

```go events.go theme={null}
package main

import (
	"fmt"
	"log"
	"time"

	"github.com/sendlayer/sendlayer-go"
)

func main() {
	sl := sendlayer.New("your-api-key")

	// Filter events for the last 24 hours
	endDate := time.Now()
	startDate := endDate.Add(-24 * time.Hour)
	event := "opened"

	events, err := sl.Events.Get(&sendlayer.GetEventsRequest{
		StartDate: &startDate,
		EndDate:   &endDate,
		Event:     event,
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Filtered events:", events.TotalRecords)
}
```

#### Event Request Parameters

The table below contains supported fields in `GetEventsRequest`.

| Field           | Type         | Required | Description                                  |
| --------------- | ------------ | -------- | -------------------------------------------- |
| `StartDate`     | `*time.Time` | No       | Start date for filtering events              |
| `EndDate`       | `*time.Time` | No       | End date for filtering events                |
| `Event`         | `string`     | No       | Filter by event type (for example, `opened`) |
| `MessageID`     | `string`     | No       | Filter by SendLayer message ID               |
| `StartFrom`     | `*int`       | No       | Starting offset for paginated event results  |
| `RetrieveCount` | `*int`       | No       | Number of records to return                  |

## Error Handling

The SDK returns typed errors you can inspect with `errors.As`.

```go theme={null}
package main

import (
	"errors"
	"fmt"
	"log"

	"github.com/sendlayer/sendlayer-go"
)

func main() {
	sl := sendlayer.New("your-api-key")

	resp, err := sl.Emails.Send(&sendlayer.SendEmailRequest{
		From:    "sender@example.com",
		To:      "recipient@example.com",
		Subject: "Test Email",
		Text:    "This is a test email",
	})
	if err != nil {
		var apiErr *sendlayer.SendLayerAPIError
		var valErr *sendlayer.SendLayerValidationError
		if errors.As(err, &apiErr) {
			fmt.Println("API error:", apiErr.Message, apiErr.StatusCode)
			return
		}
		if errors.As(err, &valErr) {
			fmt.Println("Validation error:", valErr.Error())
			return
		}
		fmt.Println("Unexpected error:", err)
		return
	}

	fmt.Println("Email sent! Message ID:", resp.MessageID)
}
```

Here is an example error response:

```bash theme={null}
Error: Invalid event name - 'opened' is not a valid event name
```

## More Go SDK Examples

<Card title="SendLayer Go SDK" icon="github" href="https://github.com/sendlayer/sendlayer-go" arrow="true" cta="View more examples">
  View more details and examples on GitHub.
</Card>
