Skip to main content

Prerequisites

Before getting started, you’ll need to:
  1. Authorize your sending domain
  2. Create and retrieve your SendLayer API key

Installation

Install the SendLayer Go SDK using the go get command:
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.
sendEmail.go
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.
sendEmail.go
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)
}
You can include both Text and Html to send plain text and HTML versions of the same email.

Send Email to Multiple Recipients

Use EmailAddress objects to send to multiple recipients, including Cc, Bcc, and ReplyTo.
sendEmail.go
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.
There are limits to the number of email recipients you can add to a single request. See our rate limiting guide to learn more.

Include Attachments in Email

Include attachments by setting the Attachments field in SendEmailRequest.
sendEmail.go
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)
}
The maximum email size SendLayer allows is 10MB. This includes both the message as well as attachment files.
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.

Email Request Parameters

The table below contains the supported fields in SendEmailRequest.
FieldTypeRequiredDescription
Fromstring or EmailAddressYesSender email, as a plain email string or EmailAddress (Email + optional Name)
Tostring, EmailAddress, or []EmailAddressYesRecipient email(s), as one address or multiple addresses
SubjectstringYesEmail subject line
TextstringYesPlain text body
HtmlstringNoHTML body
CcEmailAddress or []EmailAddressNoCarbon-copy recipients
BccEmailAddress or []EmailAddressNoBlind carbon-copy recipients
ReplyToEmailAddress or []EmailAddressNoReply-to recipient(s)
Attachments[]AttachmentNoFile attachments with Path and MIME Type
Headersmap[string]stringNoCustom email headers
Tags[]stringNoTags 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.
webhooks.go
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:
{
   "NewWebhookID": 23718
}

Get All Webhooks

To view all the webhooks you’ve created, use the Webhooks.Get() method.
webhooks.go
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:
{
  "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().
Deleting a webhook cannot be undone.
webhooks.go
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.
ParameterTypeRequiredDescription
WebhookURLstringYes (create)Webhook endpoint URL where SendLayer sends events
EventstringYes (create)Event type for the webhook subscription
webhookIdintYes (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.
events.go
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:
{
  "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.
events.go
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.
FieldTypeRequiredDescription
StartDate*time.TimeNoStart date for filtering events
EndDate*time.TimeNoEnd date for filtering events
EventstringNoFilter by event type (for example, opened)
MessageIDstringNoFilter by SendLayer message ID
StartFrom*intNoStarting offset for paginated event results
RetrieveCount*intNoNumber of records to return

Error Handling

The SDK returns typed errors you can inspect with errors.As.
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:
Error: Invalid event name - 'opened' is not a valid event name

More Go SDK Examples

SendLayer Go SDK

View more details and examples on GitHub.