# Send Email Source: https://developers.sendlayer.com/api-reference/endpoint/email sendlayer.json POST /email # Retrieve Events Source: https://developers.sendlayer.com/api-reference/endpoint/events sendlayer.json GET /events # Delete Webhook Source: https://developers.sendlayer.com/api-reference/endpoint/webhooks/delete sendlayer.json DELETE /webhooks/{id} # Get Webhooks Source: https://developers.sendlayer.com/api-reference/endpoint/webhooks/get sendlayer.json GET /webhooks # Create Webhook Source: https://developers.sendlayer.com/api-reference/endpoint/webhooks/post sendlayer.json POST /webhooks # Error Codes Source: https://developers.sendlayer.com/api-reference/error-codes List of API errors and their description ### SendLayer API Error Codes If your API call is unsuccessful, an error code and message will be returned in JSON. Below is a list of the error codes: | Code | Message | | ---- | ------------------------------------------------------------------------------------------------------------------------- | | 1 | Missing SenderAPIKey | | 2 | Missing FromName | | 3 | Missing FromEmail | | 4 | Missing ReplyToName | | 5 | Missing ReplyToEmail | | 6 | Missing ToName | | 7 | Missing ToEmail | | 8 | Missing Subject | | 9 | Missing ContentType | | 10 | Missing HTMLContent | | 11 | Missing PlainContent | | 12 | Invalid user | | 13 | Invalid sender API key | | 14 | Recipient email is suppressed | | 15 | Invalid TemplateID | | 16 | Invalid TargetListID | | 17 | Email quota reached | | 18 | Recipient name or email address is missing | | 19 | Recipient email address is invalid | | 20 | There is no recipient set for the email **OR** The number of recipients exceeds the allowed recipient email address count | | 21 | CC name or email address is missing | | 22 | CC email address is invalid | | 23 | Invalid from email address format | | 24 | BCC email addresses must be set as an array | | 25 | BCC name or email address is missing | | 26 | BCC email address is invalid | | 27 | The number of BCC email addresses exceed the allowed email address count | | 28 | Reply-To email addresses must be set as an array | | 29 | Reply-To name or email address is missing | | 30 | Reply-To email address is invalid | | 31 | The number of Reply-To email addresses exceed the allowed email address count | | 32 | Domain is not activated | | 404 | Resource not found | | 422 | Invalid request parameters | | 429 | Too many requests | ### Example Error Response ```json theme={null} { "Errors": [ { "Code": 13, "Message": "Invalid SenderAPIKey" } ] } ``` # Introduction Source: https://developers.sendlayer.com/api-reference/introduction SendLayer API endpoints Welcome to the SendLayer API endpoint reference. SendLayer provides access to its API endpoints to allow developers integrate SendLayer into their applications. Here, you'll learn about the available API endpoints and how to interact with each of the endpoints. ## Base URL SendLayer's API follows **REST** principles. All requests contain the following base URL: ``` https://console.sendlayer.com/api/v1/ ``` ## Authentication All API endpoints are authenticated using Bearer tokens. To authenticate, you'll need to add an **Authorization** header with the content of the header being `Bearer `, where token is your SendLayer API key. To learn how to access your SendLayer API key, check out our tutorial on [managing API keys](https://sendlayer.com/docs/managing-api-keys/). ``` Authorization: 'Bearer ' ``` # Rate Limits Source: https://developers.sendlayer.com/api-reference/rate-limit SendLayer API rate limits SendLayer API rate limits are applied to the API key used to make the request. ## Email Sending SendLayer API limit usage varies depending on your account plan. Below are the available plans and their respective limits. | SendLayer Plan | Emails/minute | Emails/hour | Emails/day | | -------------- | ------------- | ----------- | ---------- | | Trial | 10 | 25 | 50 | | Starter | 50 | 300 | 500 | | Business | 120 | 500 | 1000 | | Growth | 200 | 1000 | 2500 | See our detailed guide to learn more about [SendLayer rate limits](https://sendlayer.com/docs/understanding-sendlayer-rate-limiting/) ## Email Recipients When sending emails to multiple recipients, the following limits apply to all users regardless of account type. * **Send To:** 10 email addresses * **CC:** 10 email addresses * **BCC:** 5 email addresses ## Email Size When sending an email, the maximum file size per email is **10 MB**. This includes both the content and additional email attachments. # Viewing Recent Changelogs Source: https://developers.sendlayer.com/changelog SendLayer API updates ### Golang SDK Major v1 release with a revamped, struct-based request API across Email, Events, and Webhooks. #### Summary * Revamped email sending to use `SendEmailRequest` instead of positional arguments. * Aligned events querying and webhook creation with `GetEventsRequest` and `WebhookCreateRequest`. #### Details **Email** * Added `SendEmailRequest` with `From`, `To`, `Subject`, `Text`, `Html`, `Cc`, `Bcc`, `ReplyTo`, `Attachments`, `Headers`, and `Tags`. * Updated `EmailsService.Send` signature to `Send(req *SendEmailRequest) (*EmailResponse, error)`. **Events** * Added `GetEventsRequest` with `StartDate`, `EndDate`, `Event`, `MessageID`, `StartFrom`, and `RetrieveCount`. * Updated `EventsService.Get` signature to `Get(req *GetEventsRequest) (*EventsResponse, error)`. * All fields are optional; `nil` means no filters (`GET /events`). **Webhooks** * Reused `WebhookCreateRequest` as the user-facing create payload. * Updated `WebhooksService.Create` signature to `Create(req *WebhookCreateRequest) (*WebhookCreateResponse, error)`. #### Breaking Changes * `EmailsService.Send` no longer supports the old 12-argument signature. * `EventsService.Get` and `WebhooksService.Create` now require struct-based request payloads. * Existing integrations must migrate to request structs. #### Migration Example **Before** ```go theme={null} func main() { sl := sendlayer.New(os.Getenv("SENDLAYER_API_KEY")) resp, err := sl.Emails.Send( "paulie@example.com", "recipient@example.com", "Test Email", "This is a test email", "", nil, nil, nil, nil, nil, nil, ) if err != nil { log.Fatal(err) } fmt.Println("Email sent! Message ID:", resp.MessageID) } ``` **After** ```go theme={null} func main() { sl := sendlayer.New(os.Getenv("SENDLAYER_API_KEY")) resp, err := sl.Emails.Send(&sendlayer.SendEmailRequest{ From: "paulie@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) } ``` ### MCP Server Released a MCP server for AI tools like Cursor and Claude to send emails and manage webhooks/events. ### Node.js SDK Fixed TypeScript declarations resolution by pointing `"types"` to `"./dist"`. ### Ruby SDK Released a RubyGems client SDK for Ruby developers to integrate with SendLayer's API. ### Go SDK Released a client SDK for Golang developers to integrate with SendLayer's API. ### PHP SDK Released a client SDK for PHP developers to integrate with SendLayer's API. ### Node.js SDK Released a client SDK for JavaScript developers to integrate with SendLayer's API. ### Python SDK Released a client SDK for Python developers to integrate the API. # Retrieving Email Events Source: https://developers.sendlayer.com/guides/get-events Learn how to retrieve and filter email events using the SendLayer API ## Overview The SendLayer API allows you to retrieve detailed information about email events such as deliveries, opens, clicks, bounces, and more. This guide shows you how to fetch these events and apply various filters to get the specific data you need. ## Prerequisites * [Authorize your domain](https://sendlayer.com/docs/authorizing-your-domain/) * [Create or retrieve your API key](https://sendlayer.com/docs/managing-api-keys/) * [Install the SendLayer SDK](/quickstart/installation) ## Retrieving All Events To get started, you can retrieve all events associated with your account. By default, this returns the most recent 5 events. ```javascript JavaScript theme={null} import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); // Get all events (defaults to 5 most recent) const events = await sendlayer.Events.get(); console.log('Total records:', events.totalRecords); console.log('Events:', events.events); ``` ```python Python theme={null} from sendlayer import SendLayer sendlayer = SendLayer('your-api-key') # Get all events (defaults to 5 most recent) events = sendlayer.Events.get() print(f"Total records: {events['totalRecords']}") print(f"Events: {events['events']}") ``` ```php PHP theme={null} Events->get(); ``` ```ruby Ruby theme={null} require 'sendlayer' sendlayer = SendLayer::SendLayer.new('your-api-key') events = sendlayer.events.get ``` ```go Go theme={null} sl := sendlayer.New("your-api-key") all, err := sl.Events.Get(nil) ``` ```bash cURL theme={null} curl --request GET \ --url https://console.sendlayer.com/api/v1/events \ --header 'Authorization: Bearer ' ``` Replace `` with your actual SendLayer API key in the request header. ### Example Response When you retrieve events, you'll receive data in this format: ```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." } ] } ``` ## Filtering Events You can apply various filters to narrow down the events you want to retrieve. This is useful for analyzing specific time periods, event types, or individual emails. ### Filter by Date Range Retrieve events within a specific time period using Unix timestamps. ```javascript JavaScript theme={null} import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); // Filter events for the last 24 hours const startDate = Math.floor((Date.now() - 24 * 60 * 60 * 1000) / 1000); // 24 hours ago const endDate = Math.floor(Date.now() / 1000); // current time const events = await sendlayer.Events.get({ startDate: startDate, endDate: endDate }); ``` ```python Python theme={null} from sendlayer import SendLayer from datetime import datetime, timedelta sendlayer = SendLayer('your-api-key') # Filter events for the last 24 hours start_date = int((datetime.now() - timedelta(hours=24)).timestamp()) end_date = int(datetime.now().timestamp()) events = sendlayer.Events.get( start_date=start_date, end_date=end_date ) ``` ```php PHP theme={null} Events->get([ 'startDate' => time() - 24 * 60 * 60, 'endDate' => time() ]); ``` ```ruby Ruby theme={null} sendlayer = SendLayer::SendLayer.new('your-api-key') start_date = (Time.now - 24*60*60).to_i end_date = Time.now.to_i events = sendlayer.events.get( start_date: start_date, end_date: end_date ) ``` ```go Go theme={null} sl := sendlayer.New("your-api-key") end := time.Now() start := end.Add(-24 * time.Hour) events, err := sl.Events.Get(&sendlayer.GetEventsRequest{ StartDate: &start, EndDate: &end, }) ``` ```bash cURL theme={null} curl --request GET \ --url 'https://console.sendlayer.com/api/v1/events?StartDate=1746254496&EndDate=1746340896' \ --header 'Authorization: Bearer ' ``` ### Filter by Event Type You can filter events by type. Here is an example: ```javascript JavaScript theme={null} import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); // Get only opened events const openedEvents = await sendlayer.Events.get({ event: 'opened' }); // Get only bounced events const bouncedEvents = await sendlayer.Events.get({ event: 'bounced' }); ``` ```python Python theme={null} from sendlayer import SendLayer sendlayer = SendLayer('your-api-key') # Get only opened events opened_events = sendlayer.Events.get(event='opened') # Get only bounced events bounced_events = sendlayer.Events.get(event='bounced') ``` ```php PHP theme={null} Events->get([ 'event' => 'opened' ]); $bouncedEvents = $sendlayer->Events->get([ 'event' => 'bounced' ]); ``` ```ruby Ruby theme={null} sendlayer = SendLayer::SendLayer.new('your-api-key') opened_events = sendlayer.events.get(event: 'opened') bounced_events = sendlayer.events.get(event: 'bounced') ``` ```go Go theme={null} sl := sendlayer.New("your-api-key") opened, err := sl.Events.Get(&sendlayer.GetEventsRequest{ Event: "opened", }) bounced, err := sl.Events.Get(&sendlayer.GetEventsRequest{ Event: "bounced", }) ``` ```bash cURL theme={null} # Get opened events curl --request GET \ --url 'https://console.sendlayer.com/api/v1/events?Event=opened' \ --header 'Authorization: Bearer ' # Get bounced events curl --request GET \ --url 'https://console.sendlayer.com/api/v1/events?Event=bounced' \ --header 'Authorization: Bearer ' ``` Below, we've highlighted the available event types: * `opened`: Recipient opened the email * `clicked`: Recipient clicked a link in the email * `unsubscribed`: Recipient unsubscribed from emails * `complained`: Recipient marked email as spam * `delivered`: Email successfully delivered to recipient's inbox * `failed`: Email failed to deliver and bounced back * `accepted`: Email was accepted by the recipient's email server. In some cases, this may be seen as `accepted-by-system` * `rejected`: Email was rejected by the recipient's email server ### Filter by Message ID Retrieve events for a specific email using its Message ID. ```javascript JavaScript theme={null} import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); // Get events for a specific email const messageEvents = await sendlayer.Events.get({ messageId: '06e4491f-fc5a-49cb-bc57-xxxxxx' }); ``` ```python Python theme={null} from sendlayer import SendLayer sendlayer = SendLayer('your-api-key') # Get events for a specific email message_events = sendlayer.Events.get( message_id='06e4491f-fc5a-49cb-bc57-xxxxxx' ) ``` ```php PHP theme={null} Events->get([ 'messageId' => '06e4491f-fc5a-49cb-bc57-xxxxxx' ]); ``` ```ruby Ruby theme={null} sendlayer = SendLayer::SendLayer.new('your-api-key') message_events = sendlayer.events.get(message_id: '06e4491f-fc5a-49cb-bc57-xxxxxx') ``` ```go Go theme={null} sl := sendlayer.New("your-api-key") msgID := "06e4491f-fc5a-49cb-bc57-xxxxxx" events, err := sl.Events.Get(&sendlayer.GetEventsRequest{ MessageID: msgID, }) ``` ```bash cURL theme={null} curl --request GET \ --url 'https://console.sendlayer.com/api/v1/events?MessageID=06e4491f-fc5a-49cb-bc57-xxxxxx' \ --header 'Authorization: Bearer ' ``` ### Pagination and Result Limits Control how many events to retrieve and implement pagination. ```javascript JavaScript theme={null} import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); // Get 20 events starting from the 10th event const events = await sendlayer.Events.get({ startFrom: 10, retrieveCount: 20 }); ``` ```python Python theme={null} from sendlayer import SendLayer sendlayer = SendLayer('your-api-key') # Get 20 events starting from the 10th event events = sendlayer.Events.get( start_from=10, retrieve_count=20 ) ``` ```php PHP theme={null} Events->get([ 'startFrom' => 10, 'retrieveCount' => 20 ]); ``` ```ruby Ruby theme={null} sendlayer = SendLayer::SendLayer.new('your-api-key') events = sendlayer.events.get( start_from: 10, retrieve_count: 20 ) ``` ```go Go theme={null} sl := sendlayer.New("your-api-key") startFrom := 10 retrieveCount := 20 events, err := sl.Events.Get(&sendlayer.GetEventsRequest{ StartFrom: &startFrom, RetrieveCount: &retrieveCount, }) ``` ```bash cURL theme={null} curl --request GET \ --url 'https://console.sendlayer.com/api/v1/events?StartFrom=10&RetrieveCount=20' \ --header 'Authorization: Bearer ' ``` ## Combining Filters You can combine multiple filters to get very specific results. ```javascript JavaScript theme={null} import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); // Get opened events from the last 7 days, limited to 50 results const startDate = Math.floor((Date.now() - 7 * 24 * 60 * 60 * 1000) / 1000); const endDate = Math.floor(Date.now() / 1000); const events = await sendlayer.Events.get({ startDate: startDate, endDate: endDate, event: 'opened', retrieveCount: 50 }); ``` ```python Python theme={null} from sendlayer import SendLayer from datetime import datetime, timedelta sendlayer = SendLayer('your-api-key') # Get opened events from the last 7 days, limited to 50 results start_date = int((datetime.now() - timedelta(days=7)).timestamp()) end_date = int(datetime.now().timestamp()) events = sendlayer.Events.get( start_date=start_date, end_date=end_date, event='opened', retrieve_count=50 ) ``` ```php PHP theme={null} Events->get([ 'startDate' => time() - 7 * 24 * 60 * 60, 'endDate' => time(), 'event' => 'opened', 'retrieveCount' => 50 ]); ``` ```ruby Ruby theme={null} sendlayer = SendLayer::SendLayer.new('your-api-key') events = sendlayer.events.get( start_date: (Time.now - 7*24*60*60).to_i, end_date: Time.now.to_i, event: 'opened', retrieve_count: 50 ) ``` ```go Go theme={null} sl := sendlayer.New("your-api-key") end := time.Now() start := end.Add(-7 * 24 * time.Hour) retrieveCount := 50 events, err := sl.Events.Get(&sendlayer.GetEventsRequest{ StartDate: &start, EndDate: &end, Event: "opened", RetrieveCount: &retrieveCount, }) ``` ```bash cURL theme={null} curl --request GET \ --url 'https://console.sendlayer.com/api/v1/events?StartDate=1745736096&EndDate=1746340896&Event=opened&RetrieveCount=50' \ --header 'Authorization: Bearer ' ``` ## Available Parameters The events API supports the following parameters for filtering and pagination: | Parameter | Type | Required | Description | | --------------- | -------- | -------- | ------------------------------------------------------------------------------------------------------- | | `startDate` | `number` | No | Unix timestamp for the start of the date range | | `endDate` | `number` | No | Unix timestamp for the end of the date range | | `event` | `string` | No | Filter by event type (accepted, rejected, failed, delivered, opened, clicked, unsubscribed, complained) | | `messageId` | `string` | No | Filter by specific email Message ID | | `startFrom` | `number` | No | Starting position for pagination (default: 0) | | `retrieveCount` | `number` | No | Number of events to retrieve (default: 5) | ## Event Data Structure Each event contains detailed information about what happened to your email: ```json theme={null} { "Event": "opened", "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 opened.", "Ip": "10.30.126.18", "Geolocation": { "City": "San Francisco", "Region": "CA", "Country": "US" } } ``` ### Event Fields Explained * **Event**: The type of event that occurred * **LoggedAt**: Unix timestamp when the event was logged * **LogLevel**: Log level (usually "info") * **Message**: Email message details including headers and metadata * **Recipient**: The email address of the recipient * **Reason**: Human-readable description of what happened * **Ip**: IP address where the event occurred (for opens/clicks) * **Geolocation**: Geographic location data (for opens/clicks) ## Best Practices 1. **Use Date Filters**: Always specify date ranges when retrieving events to avoid overwhelming results 2. **Implement Pagination**: Use `startFrom` and `retrieveCount` for large datasets 3. **Cache Results**: Store event data locally to avoid repeated API calls 4. **Monitor Rate Limits**: Be mindful of API rate limits when making frequent requests 5. **Error Handling**: Implement proper error handling for API failures 6. **Regular Polling**: Set up regular intervals to check for new events ## FAQ SendLayer stores event data for a limited time period. This varies by account and is subject to change. Contact support for specific retention details for your account. For real-time monitoring, check every few minutes. For batch processing, hourly or daily checks are usually sufficient. All timestamps are in Unix timestamp format (seconds since epoch) and are in UTC timezone. # Managing Webhooks Source: https://developers.sendlayer.com/guides/manage-webhooks Learn how to create, retrieve, and delete webhooks using the SendLayer API ## Overview Webhooks are HTTP callbacks that allow SendLayer to notify your application in real-time when specific email events occur. Instead of polling the API to check for updates, webhooks automatically send data to your specified URL when events happen, such as when an email is opened, clicked, or bounced. ## How Webhooks Work 1. **Setup**: You create a webhook by providing a URL endpoint and specifying which events you want to monitor 2. **Monitoring**: SendLayer monitors your email activity for the specified events 3. **Notification**: When an event occurs, SendLayer sends an HTTP POST request to your webhook URL with event data 4. **Processing**: Your application receives and processes the webhook data ## Prerequisites * [Authorize your domain](https://sendlayer.com/docs/authorizing-your-domain/) * [Create or retrieve your API key](https://sendlayer.com/docs/managing-api-keys/) * A publicly accessible webhook endpoint URL * [Install the SendLayer SDK](/quickstart/installation) ## Creating a Webhook To create a webhook, you need to specify the event type you want to monitor and the URL where SendLayer should send notifications. ```javascript JavaScript theme={null} import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); const params = { url: 'https://your-domain.com/webhook', event: 'open' }; const response = await sendlayer.Webhooks.create(params); console.log('Webhook created with ID:', response.NewWebhookID); ``` ```python Python theme={null} from sendlayer import SendLayer sendlayer = SendLayer('your-api-key') params = { "url": "https://your-domain.com/webhook", "event": "open" } response = sendlayer.Webhooks.create(**params) print(f"Webhook created with ID: {response['NewWebhookID']}") ``` ```php PHP theme={null} 'https://your-domain.com/webhook', 'event' => 'open' ]; $response = $sendlayer->Webhooks->create($params); ``` ```ruby Ruby theme={null} require 'sendlayer' sendlayer = SendLayer::SendLayer.new('your-api-key') webhook = sendlayer.webhooks.create( url: 'https://your-domain.com/webhook', event: 'open' ) ``` ```go Go theme={null} sl := sendlayer.New("your-api-key") webhook, err := sl.Webhooks.Create(&sendlayer.WebhookCreateRequest{ WebhookURL: "https://your-domain.com/webhook", Event: "open", }) ``` ```bash cURL theme={null} curl --request POST \ --url https://console.sendlayer.com/api/v1/webhooks \ --header 'Authorization: Bearer ' \ --header 'Content-Type: application/json' \ --data '{ "Event": "open", "WebhookURL": "https://your-domain.com/webhook" }' ``` Replace `` with your actual SendLayer API key in the request header. ### Available Event Types You can monitor the following email events: | Event | Description | | ------------- | ------------------------------------------------- | | `delivery` | Email successfully delivered to recipient's inbox | | `open` | Recipient opened the email | | `click` | Recipient clicked a link in the email | | `bounce` | Email failed to deliver and bounced back | | `unsubscribe` | Recipient unsubscribed from emails | | `complaint` | Recipient marked email as spam | ## Retrieving Webhooks You can retrieve all webhooks associated with your account to see their current status and configuration. ```javascript JavaScript theme={null} import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); const webhooks = await sendlayer.Webhooks.get(); console.log('Webhooks:', webhooks.Webhooks); ``` ```python Python theme={null} from sendlayer import SendLayer sendlayer = SendLayer('your-api-key') webhooks = sendlayer.Webhooks.get() print("Webhooks:", webhooks['Webhooks']) ``` ```php PHP theme={null} Webhooks->get(); ``` ```ruby Ruby theme={null} sendlayer = SendLayer::SendLayer.new('your-api-key') webhooks = sendlayer.webhooks.get ``` ```go Go theme={null} sl := sendlayer.New("your-api-key") webhooks, err := sl.Webhooks.Get() ``` ```bash cURL theme={null} curl --request GET \ --url https://console.sendlayer.com/api/v1/webhooks \ --header 'Authorization: Bearer ' ``` ### Get Webhook Response Format When you retrieve webhooks, you'll receive data in this format: ```json theme={null} { "Webhooks": [ { "WebhookID": "23718", "CreatedAt": "2025-04-11 09:43:07", "UpdatedAt": "2025-04-11 09:43:07", "Status": "Enabled", "WebhookURL": "https://your-domain.com/webhook", "Event": "open", "LastResponseCode": "200", "LastResponseBody": "", "LastResponseAt": "2025-04-11 10:15:30", "LastResponseTryCounter": "0" } ] } ``` ## Deleting a Webhook You can delete a webhook by providing its ID. This action cannot be undone. ```javascript JavaScript theme={null} import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); const webhookId = 23718; await sendlayer.Webhooks.delete(webhookId); console.log('Webhook deleted successfully'); ``` ```python Python theme={null} from sendlayer import SendLayer sendlayer = SendLayer('your-api-key') webhook_id = 23718 sendlayer.Webhooks.delete(webhook_id) print("Webhook deleted successfully") ``` ```php PHP theme={null} Webhooks->delete($webhookId); ``` ```ruby Ruby theme={null} sendlayer = SendLayer::SendLayer.new('your-api-key') webhook_id = 23718 sendlayer.webhooks.delete(webhook_id) ``` ```go Go theme={null} sl := sendlayer.New("your-api-key") webhookID := 23718 _ = sl.Webhooks.Delete(webhookID) ``` ```bash cURL theme={null} curl --request DELETE \ --url https://console.sendlayer.com/api/v1/webhooks/23718 \ --header 'Authorization: Bearer ' ``` Deleting a webhook cannot be undone. You won't be able to recover or access your webhook after deleting it. ## Webhook Payload Format When SendLayer sends a webhook notification to your endpoint, it includes detailed information about the event. Below, we've provided examples of the payload for each event: ```json Open theme={null} { "event": { "method": "POST", "path": "/", "query": {}, "client_ip": "0.0.0.0", "url": "https://your-domain.com/webhook", "headers": { "host": "your-domain.com", "content-length": 320, "user-agent": "GuzzleHttp/6.5.1 curl/7.68.0 PHP/5.6.40-67+ubuntu20.04.1+deb.sury.org+1", "content-type": "application/json" }, "body": { "Signature": { "Timestamp": 1758100959, "Token": "c0a6c82bdde01faab7e857", "Signature": "3d1bf89405e4b71ed80bc240cd512aa7ed9db9dcfb17" }, "EventData": { "Event": "opened", "Domain": "example.com", "MessageID": "4331c06-2d1d-4387-969e-697835", "To": "recipient@example.com", "IPAddress": "10.30.126.18" } } } } ``` ```json Click theme={null} { "event": { "method": "POST", "path": "/", "query": {}, "client_ip": "0.0.0.0", "url": "https://your-domain.com/webhook", "headers": { "host": "your-domain.com", "content-length": 320, "user-agent": "GuzzleHttp/6.5.1 curl/7.68.0 PHP/5.6.40-67+ubuntu20.04.1+deb.sury.org+1", "content-type": "application/json" }, "body": { "Signature": { "Timestamp": 1758100959, "Token": "c0a6c82bdde01faab7e857", "Signature": "3d1bf89405e4b71ed80bc240cd512aa7ed9db9dcfb17" }, "EventData": { "Event": "clicked", "Domain": "example.com", "MessageID": "4331c06-2d1d-4387-969e-697835", "To": "recipient@example.com", "IPAddress": "10.30.126.18" } } } } ``` ```json Delivery theme={null} { "event": { "method": "POST", "path": "/", "query": {}, "client_ip": "0.0.0.0", "url": "https://your-domain.com/webhook", "headers": { "host": "your-domain.com", "content-length": 320, "user-agent": "GuzzleHttp/6.5.1 curl/7.68.0 PHP/5.6.40-67+ubuntu20.04.1+deb.sury.org+1", "content-type": "application/json" }, "body": { "Signature": { "Timestamp": 1758100959, "Token": "c0a6c82bdde01faab7e857", "Signature": "3d1bf89405e4b71ed80bc240cd512aa7ed9db9dcfb17" }, "EventData": { "Event": "delivered", "Domain": "example.com", "MessageID": "4331c06-2d1d-4387-969e-697835", "To": "recipient@example.com", } } } } ``` ```json Bounce theme={null} { "event": { "method": "POST", "path": "/", "query": {}, "client_ip": "0.0.0.0", "url": "https://your-domain.com/webhook", "headers": { "host": "your-domain.com", "content-length": 320, "user-agent": "GuzzleHttp/6.5.1 curl/7.68.0 PHP/5.6.40-67+ubuntu20.04.1+deb.sury.org+1", "content-type": "application/json" }, "body": { "Signature": { "Timestamp": 1758100959, "Token": "c0a6c82bdde01faab7e857", "Signature": "3d1bf89405e4b71ed80bc240cd512aa7ed9db9dcfb17" }, "EventData": { "Event": "bounced", "EventType": "failed", "Domain": "example.com", "MessageID": "4331c06-2d1d-4387-969e-697835", "BouncedEmailAddress": { "EmailAddress": "recipient@example.com", "Status": "smtp;550 5.1.1 User Unknown", "DiagnosticCode": "5.1.1 (bad destination mailbox address)" }, "Reason": "smtp;550 5.1.1 User Unknown", "Code": "5.1.1 (bad destination mailbox address)" } } } } ``` ```json Unsubscribe theme={null} { "event": { "method": "POST", "path": "/", "query": {}, "client_ip": "0.0.0.0", "url": "https://your-domain.com/webhook", "headers": { "host": "your-domain.com", "content-length": 320, "user-agent": "GuzzleHttp/6.5.1 curl/7.68.0 PHP/5.6.40-67+ubuntu20.04.1+deb.sury.org+1", "content-type": "application/json" }, "body": { "Signature": { "Timestamp": 1758100959, "Token": "c0a6c82bdde01faab7e857", "Signature": "3d1bf89405e4b71ed80bc240cd512aa7ed9db9dcfb17" }, "EventData": { "Event": "unsubscribed", "Domain": "example.com", "MessageID": "4331c06-2d1d-4387-969e-697835", "To": "recipient@example.com", "IPAddress": "10.30.126.18" } } } } ``` ## Best Practices 1. **Use HTTPs**: Always use HTTPs URLs for your webhook endpoints to ensure data security 2. **Monitor Status**: Regularly check your webhook status and response codes 3. **Error Handling**: Implement proper error handling for webhook processing ## FAQs You can create multiple webhooks for different events and endpoints. There's no strict limit, but it's recommended to keep the number manageable for easier maintenance. SendLayer will retry sending webhook notifications if your endpoint is unavailable. Check the `LastResponseCode` and `LastResponseTryCounter` fields to monitor delivery status. Currently, webhooks cannot be updated. You'll need to delete the existing webhook and create a new one with the updated configuration. You can use tools like webhook.site or ngrok to create temporary public URLs for testing webhook functionality during development. Check your webhook endpoint's availability, verify the URL is correct, and ensure your server can handle POST requests. Review the `LastResponseCode` field for error details. # Send Email Source: https://developers.sendlayer.com/guides/send-email Learn how to send emails using the SendLayer API ## Overview SendLayer makes it easy to send transactional and marketing emails via a simple API. This guide walks you through sending your first email using the SendLayer API, with examples for popular programming languages. ## Prerequisites * [Authorize your domain](https://sendlayer.com/docs/authorizing-your-domain/) * [Create or retrieve your API key](https://sendlayer.com/docs/managing-api-keys/) * [Install the SendLayer SDK](/quickstart/installation) ## Sending an Email After setting up your domain and API key, you can send emails using the SDK or directly via HTTP requests. ```javascript JavaScript theme={null} import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); const params = { from: 'sender@example.com', to: 'recipient@example.com', // or array of recipients subject: 'Test Email', text: 'This is a test email sent using SendLayer Node.js SDK', }; const response = await sendlayer.Emails.send(params); ``` ```python Python theme={null} from sendlayer import SendLayer sendlayer = SendLayer('your-api-key') params = { "sender": "sender@example.com", "to": "recipient@example.com", "subject": "Sending a Test Email", "text": "This is a test email sent using SendLayer's Python SDK" } response = sendlayer.Emails.send(**params) ``` ```php PHP theme={null} 'sender@example.com', 'to' => 'recipient@example.com', // or array of recipients 'subject' => 'Test Email', 'text' => "This is a test email sent using SendLayer's PHP SDK", ]; $response = $sendlayer->Emails->send($params); ``` ```ruby Ruby theme={null} require 'sendlayer' sendlayer = SendLayer::SendLayer.new('your-api-key') response = sendlayer.emails.send( from: 'sender@example.com', to: 'recipient@example.com', subject: 'Sending a Test Email', text: "This is a test email sent using SendLayer's Ruby SDK" ) ``` ```go Go theme={null} sl := sendlayer.New("your-api-key") resp, err := sl.Emails.Send(&sendlayer.SendEmailRequest{ From: "sender@example.com", To: "recipient@example.com", Subject: "Sending a Test Email", Text: "This is a test email sent using SendLayer's Go SDK", }) ``` ```bash cURL theme={null} curl --request POST \ --url https://console.sendlayer.com/api/v1/email \ --header 'Authorization: Bearer ' \ --header 'Content-Type: application/json' \ --data '{ "From": { "name": "Paulie Paloma", "email": "paulie@example.com" }, "To": [ { "name": "Pattie Paloma", "email": "pattie@exampledomain.com" } ], "Subject": "This is the email subject", "ContentType": "Text", "PlainContent": "This is a test email sent with the SendLayer API!" }' ``` Replace `` with your actual SendLayer API key in the request header. You can also send to [multiple recipients](/guides/send-email-to-multiple-recipients), add CC/BCC, and [attach files](/guides/send-email-with-attachments). SendLayer API also let's you send HTML emails. This can be useful if you'd like to use a template to send welcome emails to new users. To send HTML emails, simply update the `params` variable to include the `html` object. Then enter your HTML email as a string. ```javascript JavaScript theme={null} const params = { from: 'sender@example.com', to: 'recipient@example.com', // or array of recipients subject: 'Test Email', html: '

This is a test email sent with the SendLayer API!

', }; ``` ```python Python theme={null} params = { "sender": "sender@example.com", "to": "recipient@example.com", "subject": "Sending a Test Email", "html": "

This is a test email sent with the SendLayer API!

" } ``` ```php PHP theme={null} 'sender@example.com', 'to' => 'recipient@example.com', 'subject' => 'Test Email', 'html' => '

This is a test email sent with the SendLayer API!

', ]; ``` ```ruby Ruby theme={null} sendlayer = SendLayer::SendLayer.new('your-api-key') response = sendlayer.emails.send( from: 'sender@example.com', to: 'recipient@example.com', subject: 'Test Email', html: '

This is a test email sent with the SendLayer API!

' ) ``` ```go Go theme={null} sl := sendlayer.New("your-api-key") resp, err := sl.Emails.Send(&sendlayer.SendEmailRequest{ From: "sender@example.com", To: "recipient@example.com", Subject: "Test Email", Html: "

This is a test email sent with the SendLayer API!

", }) ``` ```bash cURL theme={null} --data '{ "From": { "name": "Paulie Paloma", "email": "paulie@example.com" }, "To": [ { "name": "Pattie Paloma", "email": "pattie@exampledomain.com" } ], "Subject": "This is the email subject", "ContentType": "HTML", "HTMLContent": "

This is a test email sent with the SendLayer API!

" }' ```
## FAQ Authorizing your domain proves ownership and improves email deliverability by reducing the likelihood of your emails being marked as spam. You can create or retrieve your API key from your SendLayer dashboard under the **Settings ยป API Keys** section. Yes, you can provide an array of email addresses in the `to` field or see our [guide](/guides/send-email-to-multiple-recipients) for more details. See our [attachments guide](/guides/send-email-with-attachments) for instructions on sending emails with attachments. Check your domain authorization, verify your API key, and review the response from the API for any error messages. You can also consult the SendLayer dashboard for delivery status and logs. # Send Email to Multiple Recipients Source: https://developers.sendlayer.com/guides/send-email-to-multiple-recipients Learn how to send emails to multiple recipients using the SendLayer API ## Overview SendLayer allows you to send emails to multiple recipients in a single API call. This guide shows you how to send emails to multiple recipients using the SendLayer API, with examples for popular programming languages. ## Prerequisites * [Authorize your domain](https://sendlayer.com/docs/authorizing-your-domain/) * [Create or retrieve your API key](https://sendlayer.com/docs/managing-api-keys/) * [Install the SendLayer SDK](/quickstart/installation) ## Sending Emails to Multiple Recipients You can send emails to multiple recipients by providing an array of email addresses in the `to` field. Each recipient will receive the same email content. **Rate Limit**: When sending to multiple recipients, be aware of SendLayer's rate limits. We recommend sending to no more than 100 recipients per request for optimal performance. For larger lists, consider using our bulk sending features or sending in batches. ```javascript JavaScript theme={null} import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); const params = { from: 'sender@example.com', to: ['recipient1@example.com', 'recipient2@example.com', 'recipient3@example.com'], subject: 'Newsletter Update', html: '

Newsletter Update

This is a newsletter sent to multiple recipients using SendLayer Node.js SDK

', }; const response = await sendlayer.Emails.send(params); ``` ```python Python theme={null} from sendlayer import SendLayer sendlayer = SendLayer('your-api-key') params = { "sender": "sender@example.com", "to": ["recipient1@example.com", "recipient2@example.com", "recipient3@example.com"], "subject": "Newsletter Update", "html": "

Newsletter Update

This is a newsletter sent to multiple recipients using SendLayer's Python SDK

" } response = sendlayer.Emails.send(**params) ``` ```php PHP theme={null} 'sender@example.com', 'to' => ['recipient1@example.com', 'recipient2@example.com', 'recipient3@example.com'], 'subject' => 'Newsletter Update', 'html' => '

Newsletter Update

This is a newsletter sent to multiple recipients using SendLayer\'s PHP SDK

', ]; $response = $sendlayer->Emails->send($params); ``` ```ruby Ruby theme={null} require 'sendlayer' sendlayer = SendLayer::SendLayer.new('your-api-key') response = sendlayer.emails.send( from: { email: 'sender@example.com', name: 'Sender Name' }, to: [ { email: 'recipient1@example.com', name: 'Recipient 1' }, { email: 'recipient2@example.com', name: 'Recipient 2' }, { email: 'recipient3@example.com', name: 'Recipient 3' } ], subject: 'Newsletter Update', html: '

Newsletter Update

This is a newsletter sent to multiple recipients using SendLayer Ruby SDK

' ) ``` ```go Go theme={null} sl := sendlayer.New("your-api-key") 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"}, {Email: "recipient3@example.com", Name: "Recipient 3"}, }, Subject: "Newsletter Update", Html: "

Newsletter Update

This is a newsletter sent to multiple recipients using SendLayer Go SDK

", }) ``` ```bash cURL theme={null} curl --request POST \ --url https://console.sendlayer.com/api/v1/email \ --header 'Authorization: Bearer ' \ --header 'Content-Type: application/json' \ --data '{ "From": { "name": "Newsletter Team", "email": "newsletter@example.com" }, "To": [ { "name": "John Doe", "email": "john@example.com" }, { "name": "Jane Smith", "email": "jane@example.com" }, { "name": "Bob Johnson", "email": "bob@example.com" } ], "Subject": "Weekly Newsletter", "ContentType": "HTML", "HTMLContent": "

Weekly Newsletter

This is our weekly newsletter sent to multiple subscribers using the SendLayer API!

" }' ```
Replace `` with your actual SendLayer API key in the request header. ## Using CC and BCC You can also use CC (Carbon Copy) and BCC (Blind Carbon Copy) to send emails to additional recipients. CC recipients will be visible to all recipients, while BCC recipients will be hidden from other recipients. ```javascript JavaScript theme={null} const params = { from: 'sender@example.com', to: ['recipient1@example.com', 'recipient2@example.com'], cc: ['cc1@example.com', 'cc2@example.com'], bcc: ['bcc1@example.com', 'bcc2@example.com'], subject: 'Meeting Invitation', html: '

Meeting Invitation

You are invited to our team meeting next week.

', }; ``` ```python Python theme={null} params = { "sender": "sender@example.com", "to": ["recipient1@example.com", "recipient2@example.com"], "cc": ["cc1@example.com", "cc2@example.com"], "bcc": ["bcc1@example.com", "bcc2@example.com"], "subject": "Meeting Invitation", "html": "

Meeting Invitation

You are invited to our team meeting next week.

" } ``` ```php PHP theme={null} 'sender@example.com', 'to' => ['recipient1@example.com', 'recipient2@example.com'], 'cc' => ['cc1@example.com', 'cc2@example.com'], 'bcc' => ['bcc1@example.com', 'bcc2@example.com'], 'subject' => 'Meeting Invitation', 'html' => '

Meeting Invitation

You are invited to our team meeting next week.

', ]; ``` ```ruby Ruby theme={null} params = { from: 'sender@example.com', to: ['recipient1@example.com', 'recipient2@example.com'], cc: ['cc1@example.com', 'cc2@example.com'], bcc: ['bcc1@example.com', 'bcc2@example.com'], subject: 'Meeting Invitation', html: '

Meeting Invitation

You are invited to our team meeting next week.

' } sendlayer = SendLayer::SendLayer.new('your-api-key') response = sendlayer.emails.send(params) ``` ```go Go theme={null} sl := sendlayer.New("your-api-key") resp, err := sl.Emails.Send(&sendlayer.SendEmailRequest{ From: "sender@example.com", To: []sendlayer.EmailAddress{ {Email: "recipient1@example.com"}, {Email: "recipient2@example.com"}, }, Subject: "Meeting Invitation", Html: "

Meeting Invitation

You are invited to our team meeting next week.

", Cc: []sendlayer.EmailAddress{{Email: "cc1@example.com"}, {Email: "cc2@example.com"}}, Bcc: []sendlayer.EmailAddress{{Email: "bcc1@example.com"}, {Email: "bcc2@example.com"}}, }) ```
## Including Names and Email Addresses You can include both names and email addresses for senders and recipients to make your emails more professional and personal. This is especially useful for newsletters, announcements, or any communication where you want to display the sender's name. ```javascript JavaScript theme={null} const params = { from: { name: 'John Smith', email: 'john@example.com' }, to: [ { name: 'Alice Johnson', email: 'alice@example.com' }, { name: 'Bob Wilson', email: 'bob@example.com' }, { name: 'Carol Davis', email: 'carol@example.com' } ], subject: 'Team Update', html: '

Team Update

Hello team, here is our weekly update.

', }; ``` ```python Python theme={null} params = { "sender": { "name": "John Smith", "email": "john@example.com" }, "to": [ { "name": "Alice Johnson", "email": "alice@example.com" }, { "name": "Bob Wilson", "email": "bob@example.com" }, { "name": "Carol Davis", "email": "carol@example.com" } ], "subject": "Team Update", "html": "

Team Update

Hello team, here is our weekly update.

" } ``` ```php PHP theme={null} [ 'name' => 'John Smith', 'email' => 'john@example.com' ], 'to' => [ [ 'name' => 'Alice Johnson', 'email' => 'alice@example.com' ], [ 'name' => 'Bob Wilson', 'email' => 'bob@example.com' ], [ 'name' => 'Carol Davis', 'email' => 'carol@example.com' ] ], 'subject' => 'Team Update', 'html' => '

Team Update

Hello team, here is our weekly update.

', ]; ``` ```ruby Ruby theme={null} params = { from: { name: 'John Smith', email: 'john@example.com' }, to: [ { name: 'Alice Johnson', email: 'alice@example.com' }, { name: 'Bob Wilson', email: 'bob@example.com' }, { name: 'Carol Davis', email: 'carol@example.com' } ], subject: 'Team Update', html: '

Team Update

Hello team, here is our weekly update.

' } sendlayer = SendLayer::SendLayer.new('your-api-key') response = sendlayer.emails.send(params) ``` ```go Go theme={null} sl := sendlayer.New("your-api-key") resp, err := sl.Emails.Send(&sendlayer.SendEmailRequest{ From: sendlayer.EmailAddress{Email: "john@example.com", Name: "John Smith"}, To: []sendlayer.EmailAddress{ {Email: "alice@example.com", Name: "Alice Johnson"}, {Email: "bob@example.com", Name: "Bob Wilson"}, {Email: "carol@example.com", Name: "Carol Davis"}, }, Subject: "Team Update", Html: "

Team Update

Hello team, here is our weekly update.

", }) ```
See our [Send Email guide](/guides/send-email) for basic email sending instructions. ## FAQ SendLayer has specific limits for multiple recipients regardless of your account type: * **Send To**: 10 email addresses * **CC**: 10 email addresses * **BCC**: 5 email addresses For more information, see our [Rate Limits](/api-reference/rate-limit) documentation. Yes, you can personalize emails by using merge tags or by sending individual emails in a loop. CC (Carbon Copy) recipients are visible to all other recipients in the email. BCC (Blind Carbon Copy) recipients are hidden from other recipients, making them ideal for privacy-sensitive communications. SendLayer provides webhook notifications for bounced emails. You can set up webhooks to receive real-time notifications when emails bounce, allowing you to clean your recipient lists. Yes, SendLayer provides tracking capabilities for email opens and clicks. You can enable tracking in your email parameters and receive webhook notifications for engagement events. Check your domain authorization, verify your API key, and review the response from the API for any error messages. You can also consult the SendLayer dashboard for delivery status and logs for each recipient. # Send Email with Attachments Source: https://developers.sendlayer.com/guides/send-email-with-attachments Learn how to send emails with attachments using the SendLayer API ## Overview SendLayer allows you to send emails with file attachments. This guide shows you how to send emails with attachments using the SendLayer API, with examples for popular programming languages. ## Prerequisites * [Authorize your domain](https://sendlayer.com/docs/authorizing-your-domain/) * [Create or retrieve your API key](https://sendlayer.com/docs/managing-api-keys/) * [Install the SendLayer SDK](/quickstart/installation) ## Sending Emails with Attachments You can attach files to your emails by including an `attachments` array in your email parameters. The SendLayer SDKs handle file encoding automatically, so you only need to provide the file path and type. The maximum file size per email is **10 MB**, including both the email content and all attachments combined. ```javascript JavaScript theme={null} import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); const params = { from: 'sender@example.com', to: 'recipient@example.com', subject: 'Document Attachment', html: '

Please find the attached document

I have attached the requested PDF file for your review.

', attachments: [ { path: './path/to/document.pdf', type: 'application/pdf' } ] }; const response = await sendlayer.Emails.send(params); ``` ```python Python theme={null} from sendlayer import SendLayer sendlayer = SendLayer('your-api-key') params = { "sender": "sender@example.com", "to": "recipient@example.com", "subject": "Document Attachment", "html": "

Please find the attached document

I have attached the requested PDF file for your review.

", "attachments": [ { "path": "./path/to/document.pdf", "type": "application/pdf" } ] } response = sendlayer.Emails.send(**params) ``` ```php PHP theme={null} ['email' => 'sender@example.com', 'name' => 'Sender Name'], 'to' => 'recipient@example.com', 'subject' => 'Document Attachment', 'html' => '

Please find the attached document

I have attached the requested PDF file for your review.

', 'attachments' => [ [ 'path' => './path/to/document.pdf', 'type' => 'application/pdf' ] ] ]; $response = $sendlayer->Emails->send($params); ``` ```ruby Ruby theme={null} require 'sendlayer' sendlayer = SendLayer::SendLayer.new('your-api-key') params = { from: { email: 'sender@example.com', name: 'Sender Name' }, to: 'recipient@example.com', subject: 'Document Attachment', html: '

Please find the attached document

I have attached the requested PDF file for your review.

', attachments: [ { path: './path/to/document.pdf', type: 'application/pdf' } ] } response = sendlayer.emails.send(params) ``` ```go Go theme={null} sl := sendlayer.New("your-api-key") resp, err := sl.Emails.Send(&sendlayer.SendEmailRequest{ From: sendlayer.EmailAddress{Email: "sender@example.com", Name: "Sender Name"}, To: "recipient@example.com", Subject: "Document Attachment", Html: "

Please find the attached document

I have attached the requested PDF file for your review.

", Attachments: []sendlayer.Attachment{ {Path: "./path/to/document.pdf", Type: "application/pdf"}, }, }) ``` ```bash cURL theme={null} curl --request POST \ --url https://console.sendlayer.com/api/v1/email \ --header 'Authorization: Bearer ' \ --header 'Content-Type: application/json' \ --data '{ "From": { "name": "Document Sender", "email": "sender@example.com" }, "To": [ { "name": "Recipient Name", "email": "recipient@example.com" } ], "Subject": "Document Attachment", "ContentType": "HTML", "HTMLContent": "

Please find the attached document

I have attached the requested PDF file for your review.

", "Attachments": [ { "Filename": "document.pdf", "Content": "JVBERi0xLjQKJcOkw7zDtsO...", "Type": "application/pdf" } ] }' ```
Replace `` with your actual SendLayer API key in the request header. The `Content` field in the cURL example should contain the actual base64-encoded file content. ## Multiple Attachments You can attach multiple files to a single email by adding more objects to the `attachments` array. ```javascript JavaScript theme={null} const params = { from: 'sender@example.com', to: 'recipient@example.com', subject: 'Multiple Attachments', html: '

Multiple Files Attached

Please find the attached documents.

', attachments: [ { path: './path/to/document.pdf', type: 'application/pdf' }, { path: './path/to/image.jpg', type: 'image/jpeg' } ] }; ``` ```python Python theme={null} params = { "sender": "sender@example.com", "to": "recipient@example.com", "subject": "Multiple Attachments", "html": "

Multiple Files Attached

Please find the attached documents.

", "attachments": [ { "path": "./path/to/document.pdf", "type": "application/pdf" }, { "path": "./path/to/image.jpg", "type": "image/jpeg" } ] } ``` ```php PHP theme={null} 'sender@example.com', 'to' => 'recipient@example.com', 'subject' => 'Multiple Attachments', 'html' => '

Multiple Files Attached

Please find the attached documents.

', 'attachments' => [ [ 'path' => './path/to/document.pdf', 'type' => 'application/pdf' ], [ 'path' => './path/to/image.jpg', 'type' => 'image/jpeg' ] ] ]; ``` ```ruby Ruby theme={null} params = { from: 'sender@example.com', to: 'recipient@example.com', subject: 'Multiple Attachments', html: '

Multiple Files Attached

Please find the attached documents.

', attachments: [ { path: './path/to/document.pdf', type: 'application/pdf' }, { path: './path/to/image.jpg', type: 'image/jpeg' } ] } ``` ```go Go theme={null} params := []sendlayer.Attachment{ {Path: "./path/to/document.pdf", Type: "application/pdf"}, {Path: "./path/to/image.jpg", Type: "image/jpeg"}, } ```
## Local and Remote File Attachments SendLayer SDKs support both local and remote file attachments. For local files, you'll need to provide the path to the file you intend to attach. For remote files, simply provide the URL. ```javascript JavaScript theme={null} const params = { from: 'sender@example.com', to: 'recipient@example.com', subject: 'Mixed Attachments', html: '

Files from different sources

Attaching both local and remote files.

', attachments: [ { path: './local-document.pdf', type: 'application/pdf' }, { path: 'https://example.com/remote-image.jpg', type: 'image/jpeg' } ] }; ``` ```python Python theme={null} params = { "sender": "sender@example.com", "to": "recipient@example.com", "subject": "Mixed Attachments", "html": "

Files from different sources

Attaching both local and remote files.

", "attachments": [ { "path": "./local-document.pdf", "type": "application/pdf" }, { "path": "https://example.com/remote-image.jpg", "type": "image/jpeg" } ] } ``` ```php PHP theme={null} 'sender@example.com', 'to' => 'recipient@example.com', 'subject' => 'Mixed Attachments', 'html' => '

Files from different sources

Attaching both local and remote files.

', 'attachments' => [ [ 'path' => './local-document.pdf', 'type' => 'application/pdf' ], [ 'path' => 'https://example.com/remote-image.jpg', 'type' => 'image/jpeg' ] ] ]; ``` ```ruby Ruby theme={null} params = { from: 'sender@example.com', to: 'recipient@example.com', subject: 'Mixed Attachments', html: '

Files from different sources

Attaching both local and remote files.

', attachments: [ { path: './local-document.pdf', type: 'application/pdf' }, { path: 'https://example.com/remote-image.jpg', type: 'image/jpeg' } ] } ``` ```go Go theme={null} params := []sendlayer.Attachment{ {Path: "./local-document.pdf", Type: "application/pdf"}, {Path: "https://example.com/remote-image.jpg", Type: "image/jpeg"}, } ```
## Supported File Types SendLayer supports a wide range of file types for attachments. Here are some common MIME types: * **Documents**: `application/pdf`, `application/msword`, `application/vnd.openxmlformats-officedocument.wordprocessingml.document` * **Spreadsheets**: `application/vnd.ms-excel`, `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` * **Images**: `image/jpeg`, `image/png`, `image/gif` * **Text Files**: `text/plain`, `text/csv` * **Archives**: `application/zip`, `application/x-rar-compressed` See our [Send Email guide](/guides/send-email) for basic email sending instructions. ## FAQ The maximum file size per email is **10 MB**, which includes both the email content and all attachments combined. If you need to send larger files, consider using cloud storage services and including download links in your emails. You can attach multiple files to a single email, but the total size of all attachments plus the email content must not exceed 10 MB. There is no specific limit on the number of files, only the total size limit. SendLayer supports most common file formats including PDFs, Word documents, Excel spreadsheets, images (JPEG, PNG, GIF), text files, and compressed archives. The file type should be specified using the appropriate MIME type. The SendLayer SDKs handle file encoding automatically. Simply provide the file path (for local files) or URL (for remote files) along with the MIME type. The SDK will read and encode the file for you. Yes, you can attach files when sending to multiple recipients. The same attachment will be sent to all recipients in the email. See our [Send Email to Multiple Recipients](/guides/send-email-to-multiple-recipients) guide for more details. If your attachment exceeds the 10 MB limit, consider compressing the file, using a cloud storage service and including a download link, or splitting the content into multiple emails with smaller attachments. # SendLayer MCP Server Source: https://developers.sendlayer.com/integrations/ai-tools/mcp-server Learn how to use the SendLayer MCP server to send email and manage webhooks/events directly from AI tools like Cursor and Claude. ## Overview The SendLayer MCP server exposes tools for sending email and managing webhooks/events using the SendLayer Node.js SDK. You can use it from AI tools like Cursor and Claude to run local scripts, chat with an AI model, and send results to yourself or your team without wiring up HTTP calls manually. ## What Is MCP? MCP (Model Context Protocol) is a protocol that allows AI tools to interact with external services and data sources. It's a way to extend the capabilities of AI tools by allowing them to use external tools and data sources. ## Tools * **send-email**: Send a message (plain text or HTML) with CC/BCC, reply-to, tags, headers, and attachments. * **get-events**: Query events with optional filters. * **list-webhooks**: List registered webhooks. * **create-webhook**: Create a webhook. * **delete-webhook**: Delete a webhook by ID. ## Prerequisites * A SendLayer account and API key ([get your API key](https://app.sendlayer.com/)) * A verified sending domain ([authorize your domain](https://sendlayer.com/docs/authorizing-your-domain/)) * Cursor or Claude Desktop installed ## Connecting to the MCP Server The easiest way to get started is to connect to the hosted SendLayer MCP server. No local installation is required. ### Cursor Use the direct link below to install the MCP server in Cursor: [![Install MCP Server](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/en-US/install-mcp?name=sendlayer\&config=eyJ0eXBlIjoidXJsIiwidXJsIjoiaHR0cHM6Ly9tY3Auc2VuZGxheWVyLmNvbSIsImhlYWRlcnMiOnsieC1zZW5kbGF5ZXItYXBpLWtleSI6IllPVVJfU0VORExBWUVSX0FQSV9LRVkifX0%3D) This will open the MCP server installation page in Cursor. Enter your SendLayer API key and click **Install**. Cursor MCP Server Installation #### Manual Installation If you're not using the direct link, open the command palette (`cmd`+`shift`+`p` on macOS or `ctrl`+`shift`+`p` on Windows) and choose **Cursor Settings**. Then, select **Tools & MCP** from the left sidebar and click **New MCP server**. Cursor MCP Server Manual Installation In the `mcp.json` file, add the following config: ```json theme={null} { "mcpServers": { "sendlayer": { "type": "url", "url": "https://mcp.sendlayer.com", "headers": { "x-sendlayer-api-key": "YOUR_SENDLAYER_API_KEY" } } } } ``` Be sure to replace `YOUR_SENDLAYER_API_KEY` with your actual SendLayer API key from `app.sendlayer.com`. After saving the file, restart Cursor and verify the MCP server is connected. You can now use commands like โ€œsend an email to [recipient@example.com](mailto:recipient@example.com)โ€ in Agent mode. ### Claude Code Run the following command on your terminal to configure the MCP server: ```bash theme={null} claude mcp add --scope user --transport http sendlayer-mcp https://mcp.sendlayer.com --header "Authorization: Bearer YOUR_SENDLAYER_API_KEY" ``` Be sure to replace `YOUR_SENDLAYER_API_KEY` with your actual SendLayer API key. ### Gemini-CLI Open a terminal and run the following command to edit your `~/.gemini/settings.json` file: ```bash theme={null} nano ~/.gemini/settings.json ``` Then, add the following lines to the file and save it: ```json theme={null} { "mcpServers": { "sendlayer": { "httpUrl": "https://mcp.sendlayer.com", "headers": { "x-sendlayer-api-key": "YOUR_SENDLAYER_API_KEY", "Content-Type": "application/json" }, "timeout": 5000 } } } ``` Be sure to replace `YOUR_SENDLAYER_API_KEY` with your actual SendLayer API key. To test the connection, run the following command: ```bash theme={null} gemini mcp list ``` You should see the `sendlayer` server in the list. You can now use the `sendlayer` server to send emails and manage webhooks/events. ### Windsurf Open your Windsurf settings page. Then select the **Cascade** sidebar menu and click **Open MCP Marketplace**. Windsurf MCP Marketplace Then, click the settings icon to open the `mcp_config.json` file. Windsurf MCP Settings Once the file is open, add the following lines to the file and save it: ```json theme={null} { "mcpServers": { "sendlayer": { "serverUrl": "https://mcp.sendlayer.com", "headers": { "x-sendlayer-api-key": "YOUR_SENDLAYER_API_KEY" } } } } ``` Be sure to replace `YOUR_SENDLAYER_API_KEY` with your actual SendLayer API key. ## Features * Send plain text and HTML emails * Send emails with attachments * Add CC and BCC recipients * Customize the sender email (verified domains only) * Create, list, and delete webhooks * Retrieve and filter email events # Installation Source: https://developers.sendlayer.com/quickstart/installation Learn how to install the SendLayer SDKs ## Overview This guide shows you how to install the SendLayer SDKs for popular languages so you can start integrating quickly. We currently provide SDKs for Node.js, Python, PHP, Ruby, and Go. ## Prerequisites Before using the SendLayer API, make sure you've: * Authorized your [sending domain](https://sendlayer.com/docs/authorizing-your-domain/) * Created or retrieved your [SendLayer API key](https://sendlayer.com/docs/managing-api-keys/) ## Node.js Install the SendLayer Node.js SDK using your preferred package manager. ```bash npm theme={null} npm install sendlayer ``` ```bash yarn theme={null} yarn add sendlayer ``` #### Validate Installation Create a file (for example, `checkInstall.js`) and run a quick import: ```javascript checkInstall.js theme={null} import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); console.log('SendLayer initialized:', !!sendlayer); ``` Replace `'your-api-key'` with your actual API key. See our [Node.js SDK guide](/sdks/nodejs) for full usage examples. ## Python Install the SendLayer Python SDK via `pip`: ```bash theme={null} pip install sendlayer ``` #### Validate Installation Create a file (for example, `check_install.py`) and run: ```python check_install.py theme={null} from sendlayer import SendLayer sendlayer = SendLayer('your-api-key') print('SendLayer initialized:', bool(sendlayer)) ``` Replace `'your-api-key'` with your actual API key. See our [Python SDK guide](/sdks/python) for full usage examples. ## PHP Install the SendLayer PHP SDK with Composer: ```bash theme={null} composer require sendlayer/sendlayer-php ``` #### Validate Installation Create a file (for example, `checkInstall.php`) and run: ```php checkInstall.php theme={null} Replace `'your-api-key'` with your actual API key. See our [PHP SDK guide](/sdks/php) for full usage examples. ## Ruby Install the SendLayer Ruby SDK via RubyGems: ```bash theme={null} gem install sendlayer ``` #### Validate Installation Create a file (for example, `check_install.rb`) and run: ```ruby check_install.rb theme={null} require 'sendlayer' sendlayer = SendLayer::SendLayer.new('your-api-key') puts "SendLayer initialized: #{!sendlayer.nil?}" ``` Replace `'your-api-key'` with your actual API key. See our [Ruby SDK guide](/sdks/ruby/send-with-ruby) for full usage examples. ## Go Install the SendLayer Go SDK using `go get`: ```bash theme={null} go get github.com/sendlayer/sendlayer-go ``` #### Validate Installation Create a file (for example, `check_install.go`) and run: ```go check_install.go theme={null} package main import ( "fmt" "github.com/sendlayer/sendlayer-go" ) func main() { sl := sendlayer.New("your-api-key") fmt.Println("SendLayer initialized:", sl != nil) } ``` Replace `'your-api-key'` with your actual API key. See our [Go SDK guide](/sdks/go/send-with-go) for full usage examples. ## Next Steps * Send your first email: [Send Email](/guides/send-email) * Add attachments: [Send Email with Attachments](/guides/send-email-with-attachments) * Send to multiple recipients: [Send Email to Multiple Recipients](/guides/send-email-to-multiple-recipients) * Manage webhooks: [Managing Webhooks](/guides/manage-webhooks) * Retrieve events: [Retrieving Email Events](/guides/get-events) ## Troubleshooting * Ensure your environment can make outbound HTTPS requests * Verify your API key is correct and active * If installation fails, update your package manager (`npm`, `yarn`, `pip`, or `composer`) and try again * Check language version requirements (Node.js 16+, Python 3.8+, PHP 7.4+) # Quickstart Source: https://developers.sendlayer.com/quickstart/introduction Learn how to quickly setup and use SendLayer email API to send transactional emails ## Prerequisites Before you can use the SendLayer API, you'll need to [authorize your sending domain](https://sendlayer.com/docs/authorizing-your-domain/). This is an important step as it proves domain ownership and improves email deliverability. After authorizing your domain, you'll need to create/retrieve your [API key](https://sendlayer.com/docs/managing-api-keys/). An API key is used to authenticate API requests. ## Installation Run the command below to install the SendLayer SDK for your preferred programming language: ```bash javascript theme={null} npm install sendlayer ``` ```bash python theme={null} pip install sendlayer ``` ```bash php theme={null} composer require sendlayer/sendlayer-php ``` ```bash ruby theme={null} gem install sendlayer ``` ```bash go theme={null} go get github.com/sendlayer/sendlayer-go ``` ## Sending an email Once, you've installed the SDK, you can import it directly into your codebase and interact with the API. Here's an example of how to send an email using the SendLayer API: ```javascript JavaScript theme={null} import { SendLayer } from 'sendlayer'; // Initialize the email client const sendlayer = new SendLayer('your-api-key'); const params = { from: 'sender@example.com', to:'recipient@example.com', // or array of recipients subject: 'Test Email', text: 'This is a test email' } // Send a simple email const response = await sendlayer.Emails.send(params); ``` ```python Python theme={null} from sendlayer import SendLayer # Initialize the email client with your API key sendlayer = SendLayer("your-api-key") # Send an email response = sendlayer.Emails.send( sender="sender@example.com", to="recipient@example.com", subject="Test Email", text="This is a test email" ) ``` ```php PHP theme={null} Emails->send([ 'from' => 'sender@example.com', 'to' => 'recipient@example.com', 'subject' => 'Test Email', 'text' => 'This is a test email' ]); ?> ``` ```ruby Ruby theme={null} require 'sendlayer' sendlayer = SendLayer::SendLayer.new('your-api-key') response = sendlayer.emails.send( from: 'sender@example.com', to: 'recipient@example.com', subject: 'Test Email', text: 'This is a test email' ) ``` ```go Go theme={null} package main import ( "fmt" "log" "github.com/sendlayer/sendlayer-go" ) func main() { // Initialize the email 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) } ``` ```bash cURL theme={null} curl --request POST \ --url https://console.sendlayer.com/api/v1/email \ --header 'Authorization: Bearer ' \ --header 'Content-Type: application/json' \ --data '{ "From": { "name": "Paulie Paloma", "email": "paulie@example.com" }, "To": [ { "name": "Pattie Paloma", "email": "pattie@exampledomain.com" } ], "Subject": "This is the email subject", "ContentType": "HTML", "HTMLContent": "

This is a test email sent with the SendLayer API!

" }' ```
If you're using the `cURL` option, make sure to replace `` with your SendLayer API key in the request header. SendLayer API also allows you to send emails to [multiple recipients](/guides/send-email-to-multiple-recipients), include BCC and CC addresses, [attach files](/guides/send-email-with-attachments) to your email messages. See our guide to learn more about [sending emails using SendLayer API](/guides/send-email). ## SDK reference SendLayer offers SDK libraries for popular programming languages that simplify the process of integrating with the API. We currently offer/support the following SDKs: Learn how to use the SendLayer's Node.js SDK Learn how to use SendLayer's Python SDK. Learn how to use SendLayer's PHP SDK. Learn how to use SendLayer's Ruby SDK. Learn how to use SendLayer's Go SDK. # Send email with Go Source: https://developers.sendlayer.com/sdks/go/send-with-go Learn how to send emails from a Go application using 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 Go 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: "

This is a test email sent with the SendLayer API!

", }) 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`. ```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: "

This is a test email!

", 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](/api-reference/rate-limit) guide to learn more. #### 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: "

This is a test email!

", 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](/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 values: * 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) } ``` 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()`. Deleting a webhook cannot be undone. ```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 examples View more details and examples on GitHub. # Send email with Node.js Source: https://developers.sendlayer.com/sdks/nodejs/introduction Learn how to install and use the SendLayer Node.js 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 Node.js SDK using the command: ```bash npm theme={null} npm install sendlayer ``` ```bash yarn theme={null} yarn add sendlayer ``` ## Usage After the installation completes, you're ready to start integrating the SDK to your code. The SDK includes modules to send emails, manage webhooks and events. ### Sending an Email Create a new `.js` file or edit an existing one. Then import the `SendLayer` module. Once done, you'll need to initialize the module with your SendLayer API key. ```javascript sendEmail.js theme={null} import { SendLayer } from 'sendlayer'; // Initialize the email client with your API key const sendlayer = new SendLayer('your-api-key'); // Send an email const response = await sendlayer.Emails.send({ from: 'sender@example.com', to: 'recipient@example.com', subject: 'Test Email', text: 'This is a test email' }); console.log('Email sent! Message ID:', response); ``` #### Sending HTML Emails To send HTML emails, simply include the `html` parameter to the `send()` method. ```javascript sendEmail.js theme={null} import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); // Send an email const response = await sendlayer.Emails.send({ from: 'sender@example.com', to: 'recipient@example.com', subject: 'Test Email', html: '

This is a test email sent with the SendLayer API!

' }); ``` You can include the `text` parameter to have a plain text and HTML version of your email message #### Sending to Multiple Recipients You can send emails to multiple recipients including `"Cc"` and `"BCC"` email addresses. ```javascript sendEmail.js theme={null} import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); // Send to multiple recipients const response = await sendlayer.Emails.send({ from: {email: 'sender@example.com', name: 'Sender Name'}, to: [ { email: 'recipient1@example.com', name: 'Recipient 1' }, { email: 'recipient2@example.com', name: 'Recipient 2' } ], subject: 'Complex Email', html: '

This is a test email!

', text: 'This is a test email!', cc: [{ email: 'cc@example.com', name: 'CC Recipient' }], bcc: [{ email: 'bcc@example.com', name: 'BCC Recipient' }], replyTo: [{ email: 'reply@example.com', name: 'Reply To' }], }); ``` Each recipient field is an array containing the recipient's `name` and `email` as objects. 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. #### Including Attachments You can include attachments to your email message by adding the `attachments` parameter to the email payload. ```javascript sendEmail.js theme={null} import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); // Send email with attachments const response = await sendlayer.Emails.send({ from: {email: 'sender@example.com', name: 'Sender Name'}, to: [ { email: 'recipient1@example.com', name: 'Recipient' } ], subject: 'Complex Email', html: '

This is a test email!

', attachments: [{ path: 'path/to/file.pdf', type: 'application/pdf', }] }); ``` The maximum email size SendLayer allows is 10MB. This includes both the message as well as attachment files. Simply replace the `path` parameter with the path to the attachment file you wish to attach and specify the correct `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 Parameters Below is a table containing the supported parameters for sending emails in Node.js using SendLayer SDK. | Parameter | Type | Required | Description | | ------------- | -------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------- | | `to` | `string` or `array` | Yes | Email address(es) of the recipient(s). Can be a single email string or an array of objects with 'email' and 'name' keys | | `from` | `string` or `object` | Yes | Email address of the sender. Can be a single email string or an object with 'email' and 'name' keys | | `subject` | `string` | Yes | Subject line of the email | | `text` | `string` | No | Plain text version of the email content | | `html` | `string` | No | HTML version of the email content | | `cc` | `string` or `array` | No | CC email address(es). Can be a single email string or an array of objects containing CC recipient email addresses and names | | `bcc` | `string` or `array` | No | BCC email address(es). Can be a single email string or an array of objects containing BCC recipient email addresses and names | | `replyTo` | `string` or `array` | No | ReplyTo email address. Can be a single email string or an object containing reply-to email address and name | | `tags` | `array` | No | Array of strings for tagging emails | | `headers` | `object` | No | Object containing custom headers | | `attachments` | `array` | No | Array of objects containing file paths and MIME types for attachments | ### Managing Webhooks With the SendLayer Node.js SDK, you can create new webhook, view all webhooks you've created and also delete a specific webhook. #### Creating a New Webhook To create a new webhook, you'll need to first import the SendLayer module and initialize it with your API key. Then call the `Webhooks.create()` method and specify the required parameters. This method requires the `url` and `event` parameters. ```javascript webhooks.js theme={null} import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); params = { url: 'https://your-domain.com/webhook', event: 'open' } // Create a webhook const webhook = await sendlayer.Webhooks.create(params); ``` The `event` parameter is constrained to the following options: * bounce * click * open * unsubscribe * complaint * delivery Example success response for new webhook: ```json theme={null} { "NewWebhookID": 23718 } ``` #### Getting All Webhooks To view all the webhooks you've created, use the `Webhooks.get()` method. ```javascript webhooks.js theme={null} import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); // Get all webhooks const webhooks = await sendlayer.Webhooks.get(); ``` 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" } ] } ``` #### Deleting a Webhook To delete a specific webhook, use the `Webhooks.delete()` method. This method accepts one required parameter `webhookId` that needs to be a number. Deleting a webhook cannot be undone. You won't be able to recover or access your webhook after deleting it. ```javascript webhooks.js theme={null} import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); // Delete a webhook const webhookId = 23718; await sendlayer.Webhooks.delete(webhookId); ``` #### Webhooks Parameters The table below contains details about the supported parameters in the `Webhooks` module. | Parameter | Type | Required | Description | | ----------- | -------- | -------- | ----------------------------------------------------------------------------------------------- | | `url` | `string` | Yes | The webhook endpoint URL where events will be sent | | `event` | `string` | Yes | The type of event to listen for. Options: bounce, click, open, unsubscribe, complaint, delivery | | `webhookId` | `number` | Yes | Unique identifier for the webhook (used in delete operation) | ### Retrieving Email Events You can view all events connected to your API key. #### Getting All Events To get started, import the SendLayer module and initialize it with your API key. Then call the `Events.get()` method to retrieve all events. The `Events.get()` method retrieves the top 5 events in your account if no filter parameter is specified. ```javascript events.js theme={null} import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); // Get all events const events = await sendlayer.Events.get(); ``` 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." } ] } ``` #### Filtering Events The `Events.get()` method in the `SendLayer` module accepts some optional parameters. These parameters can be used to filter the API response. Here is an example: ```javascript events.js theme={null} import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); // Filter events for the last 4 hours const events = await sendlayer.Events.get({ startDate: new Date(Date.now() - 4 * 60 * 60 * 1000), // 4 hours ago endDate: new Date(), // current time event: 'opened' }); ``` #### Events Parameters The table below contains details about the available parameters in the `Events` module. | Parameter | Type | Required | Description | | --------------- | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `startDate` | `Date` | No | Start date for filtering events | | `endDate` | `Date` | No | End date for filtering events | | `event` | `string` | No | Filter the API request by the type of event. Supported events include: `accepted`, `rejected`, `delivered`, `opened`, `clicked`, `unsubscribed`, `complained`, `failed` | | `messageId` | `string` | No | Filter by the email `MessageId` | | `startFrom` | `number` | No | Specify a starting number for the email filter | | `retrieveCount` | `number` | No | This parameter controls the number of event records that'll be displayed. It defaults to 5 if none is specified | ## Error Handling The SDK provides custom error types (`SendLayerError`, `SendLayerAPIError`) for better error handling. You can use try/catch blocks to handle errors when sending emails: ```javascript theme={null} import { SendLayer, SendLayerError, SendLayerAPIError } from 'sendlayer'; const sendlayer = new SendLayer('your-api-key'); try { const response = await sendlayer.Emails.send({ from: 'sender@example.com', to: 'recipient@example.com', subject: 'Test Email', text: 'This is a test email' }); } catch (error) { if (error.name === 'SendLayerAPIError') { console.error('API error:', error.message); } else { console.error('Error:', error.message); } } ``` Here is an example error response: ```bash theme={null} Error: Invalid event name - 'opened' is not a valid event name ``` ## More Examples View more details and examples on GitHub. # Send email with Express.js Source: https://developers.sendlayer.com/sdks/nodejs/send-with-expressjs Learn how to send emails from an Express.js server using the SendLayer Node.js SDK. ## Prerequisites * Node.js 16 or later * An Express 4 or Express 5 project * Authorize your [sending domain](https://sendlayer.com/docs/authorizing-your-domain/) * Create or retrieve your [SendLayer API key](https://sendlayer.com/docs/managing-api-keys/) ## Installation Install the SDK alongside Express and `dotenv`. ```bash npm theme={null} npm install express sendlayer dotenv ``` ```bash yarn theme={null} yarn add express sendlayer dotenv ``` ```bash pnpm theme={null} pnpm add express sendlayer dotenv ``` ## Storing your API key Create a `.env` file in your project root and add the key. ```bash .env theme={null} SENDLAYER_API_KEY=your-api-key PORT=3000 ``` Add `.env` to `.gitignore` so the key never reaches version control. ## Creating the email client Initialize the client in its own module and export it. A single instance serves every route in the application. ```javascript src/sendlayer.js theme={null} import 'dotenv/config'; import { SendLayer } from 'sendlayer'; if (!process.env.SENDLAYER_API_KEY) { throw new Error('SENDLAYER_API_KEY is not set'); } export const sendlayer = new SendLayer(process.env.SENDLAYER_API_KEY); ``` The startup check fails fast on a missing key. Without it, the first request would be the place the problem surfaces. These examples use ES modules. Add `"type": "module"` to your `package.json`, or convert the imports to `require()` calls if your project uses CommonJS. ## Sending an email from a route Add a POST route that reads JSON from the request body and calls `Emails.send()`. ```javascript src/server.js theme={null} import express from 'express'; import { sendlayer } from './sendlayer.js'; const app = express(); app.use(express.json()); app.post('/api/send-email', async (req, res) => { const { name, email, message } = req.body; const response = await sendlayer.Emails.send({ from: { email: 'sender@example.com', name: 'Acme Support' }, to: [{ email: 'support@example.com', name: 'Support Team' }], replyTo: [{ email, name }], subject: `New message from ${name}`, text: message, }); res.status(200).json({ messageId: response }); }); const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Server listening on port ${port}`); }); ``` The `express.json()` middleware parses the request body. Without it, `req.body` is undefined. The sender email address must match a domain you have authorized in SendLayer. ## Validating input before sending Reject malformed requests before they reach the API. This saves a round trip and returns a clearer error to the caller. ```javascript src/routes/email.js theme={null} import express from 'express'; import { sendlayer } from '../sendlayer.js'; const router = express.Router(); router.post('/send-email', async (req, res, next) => { const { email, subject, message } = req.body; if (!email || !subject || !message) { return res.status(400).json({ error: 'The email, subject, and message fields are required.', }); } try { const response = await sendlayer.Emails.send({ from: 'sender@example.com', to: email, subject, text: message, }); res.json({ messageId: response }); } catch (error) { next(error); } }); export default router; ``` Mount the router in your application file. ```javascript src/server.js theme={null} import express from 'express'; import emailRoutes from './routes/email.js'; const app = express(); app.use(express.json()); app.use('/api', emailRoutes); ``` ## Sending HTML emails Add the `html` parameter for rich content. Include `text` as a fallback for clients that block HTML. ```javascript src/routes/welcome.js theme={null} import express from 'express'; import { sendlayer } from '../sendlayer.js'; const router = express.Router(); router.post('/welcome', async (req, res, next) => { try { const response = await sendlayer.Emails.send({ from: { email: 'hello@example.com', name: 'Acme' }, to: req.body.email, subject: 'Welcome to Acme', html: `

Welcome aboard

Your account is ready. Sign in to get started.

`, text: 'Your account is ready. Sign in at https://example.com/login to get started.', tags: ['welcome-email'], }); res.json({ messageId: response }); } catch (error) { next(error); } }); export default router; ``` The `tags` array labels the message. Tags show up in your event history, which helps you separate welcome emails from other traffic. ## Testing the endpoint Start the developmentserver. ```bash theme={null} node src/server.js ``` Then post a request from another terminal using cURL. ```bash theme={null} curl --request POST \ --url http://localhost:3000/api/send-email \ --header 'Content-Type: application/json' \ --data '{ "name": "Paulie Paloma", "email": "paulie@example.com", "message": "Testing the send endpoint." }' ``` A successful request returns the message ID: ```json theme={null} { "messageId": "06e4491f-fc5a-49cb-bc57-xxxxxx" } ``` Open the **Email logs** page in your SendLayer dashboard to confirm delivery. ## Next steps Review every method and parameter in the Node.js SDK. Create, list, and delete webhook subscriptions. Query delivery events for any message. Understand recipient and request limits. # Send Email With Next.js Source: https://developers.sendlayer.com/sdks/nodejs/send-with-nextjs Learn how to send emails from a Next.js application using the SendLayer Node.js SDK. ## Prerequisites * A Next.js project (version 13.4 or later for the App Router) * Node.js 16 or later * Authorize your [sending domain](https://sendlayer.com/docs/authorizing-your-domain/) * Create or retrieve your [SendLayer API key](https://sendlayer.com/docs/managing-api-keys/) ## Installation Install the SendLayer Node.js SDK in your project root. ```bash npm theme={null} npm install sendlayer ``` ```bash yarn theme={null} yarn add sendlayer ``` ```bash pnpm theme={null} pnpm add sendlayer ``` ## Storing your API key Add your API key to `.env.local` in the project root. ```bash .env.local theme={null} SENDLAYER_API_KEY=your-api-key ``` Never prefix the key with `NEXT_PUBLIC_`. Any variable with that prefix ships to the browser, which exposes your credentials to every visitor. Add `.env.local` to your `.gitignore` file so the key stays out of version control. ## Sending an email from a route handler Create a Route Handler at `app/api/send-email/route.js`. Next.js runs this file on the server only, so the SDK and your API key remain private. ```javascript app/api/send-email/route.js theme={null} import { NextResponse } from 'next/server'; import { SendLayer } from 'sendlayer'; const sendlayer = new SendLayer(process.env.SENDLAYER_API_KEY); export async function POST(request) { const { name, email, message } = await request.json(); const response = await sendlayer.Emails.send({ from: { email: 'sender@example.com', name: 'Acme Support' }, to: [{ email: 'support@example.com', name: 'Support Team' }], replyTo: [{ email, name }], subject: `New contact form message from ${name}`, text: message, }); return NextResponse.json({ messageId: response }, { status: 200 }); } ``` The `replyTo` field points at the person who filled in the form. Support agents can then reply directly from their inbox. Use a `from` address on a domain you authorized in SendLayer. Sending from an unauthorized domain causes the request to fail. ## Submitting the form from a client component Create a client component that posts JSON to the route handler. ```javascript app/contact/ContactForm.jsx theme={null} 'use client'; import { useState } from 'react'; export default function ContactForm() { const [status, setStatus] = useState('idle'); async function handleSubmit(event) { event.preventDefault(); setStatus('sending'); const formData = new FormData(event.currentTarget); const response = await fetch('/api/send-email', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: formData.get('name'), email: formData.get('email'), message: formData.get('message'), }), }); setStatus(response.ok ? 'sent' : 'error'); } return (