### Install Development Dependencies
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Installs development dependencies required for running unit tests using pip.
```bash
pip install -e ".[dev]"
```
--------------------------------
### Install MailerSend Python SDK
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/QUICK_START.md
Install the MailerSend Python SDK using pip. Requires Python 3.10+.
```bash
pip install mailersend
```
--------------------------------
### Install MailerSend Python SDK
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Install the MailerSend Python SDK using pip. Ensure you have Python 3.7+.
```bash
pip install mailersend
```
--------------------------------
### SmsPersonalization Usage Example
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/types.md
Demonstrates how to create an instance of the SmsPersonalization model with a phone number and associated data.
```python
personalization = SmsPersonalization(
phone_number="+14155552671",
data={"name": "John", "code": "123456"}
)
```
--------------------------------
### Get List of Webhooks
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves a list of all configured webhooks for a specific domain.
```python
from mailersend import MailerSendClient, WebhooksBuilder
ms = MailerSendClient()
request = (WebhooksBuilder()
.domain_id("domain-id")
.build_webhooks_list_request())
response = ms.webhooks.list_webhooks(request)
```
--------------------------------
### Initialize EmailBuilder
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/api-reference/email-builder.md
Start building an email request using the EmailBuilder class. This is the entry point for constructing emails.
```python
builder = EmailBuilder()
```
--------------------------------
### HeaderDict Usage Example
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/types.md
Demonstrates the usage of HeaderDict for accessing header values using both bracket and dot notation.
```python
headers = HeaderDict({"content-type": "application/json"})
# Both work:
headers["content-type"]
headers.content_type # Dashes converted to underscores
# Both return the same value
```
--------------------------------
### Get a list of invites
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves a paginated list of pending user invitations.
```APIDOC
## Get a list of invites
### Description
Retrieves a paginated list of pending user invitations.
### Method
```python
ms.users.list_invites(request)
```
### Parameters
#### Request Body (Implicitly built by UsersBuilder)
- **page** (int) - Optional - The page number to retrieve.
- **limit** (int) - Optional - The number of results per page.
```
--------------------------------
### Get a list of templates
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves a paginated list of all templates associated with a specific domain.
```APIDOC
## Get a list of templates
### Description
Retrieves a paginated list of all templates associated with a specific domain.
### Method
```python
ms.templates.list_templates(request)
```
### Parameters
This method uses a `TemplatesBuilder` to construct the request.
- `domain_id` (string) - Required - The ID of the domain.
- `page` (integer) - Optional - The page number for pagination. Defaults to 1.
- `limit` (integer) - Optional - The number of templates to return per page. Defaults to 25.
### Request Example
```python
from mailersend import MailerSendClient, TemplatesBuilder
ms = MailerSendClient()
request = (
TemplatesBuilder()
.domain_id("domain-id")
.page(1)
.limit(25)
.build_templates_list_request()
)
```
### Response
(Details not provided in source)
```
--------------------------------
### Get a list of webhooks
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves a list of all webhooks configured for a specific domain.
```APIDOC
## Get a list of webhooks
### Description
Retrieves a list of all webhooks configured for a specific domain.
### Method
GET (inferred from list_webhooks)
### Endpoint
/v1/webhooks (inferred)
### Parameters
#### Query Parameters
- **domain_id** (string) - Required - The ID of the domain to list webhooks for.
### Request Example
```python
from mailersend import MailerSendClient
from mailersend import WebhooksBuilder
ms = MailerSendClient()
request = (WebhooksBuilder()
.domain_id("domain-id")
.build_webhooks_list_request())
response = ms.webhooks.list_webhooks(request)
```
### Response
#### Success Response (200)
- **data** (array) - A list of webhook objects.
- Each object contains:
- **id** (string) - The unique identifier for the webhook.
- **domain_id** (string) - The ID of the associated domain.
- **url** (string) - The URL of the webhook.
- **name** (string) - The name of the webhook.
- **events** (array of strings) - The events the webhook is subscribed to.
- **enabled** (boolean) - The status of the webhook (true/false).
- **created_at** (string) - The timestamp when the webhook was created.
- **updated_at** (string) - The timestamp when the webhook was last updated.
```
--------------------------------
### Get a list of webhooks
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves a list of all webhooks configured for a specific domain.
```APIDOC
## Get a list of webhooks
### Description
Retrieves a list of all webhooks configured for a specific domain.
### Method
```python
ms.webhooks.list_webhooks(request)
```
### Parameters
This method uses a `WebhooksBuilder` to construct the request.
- `domain_id` (string) - Required - The ID of the domain.
### Request Example
```python
from mailersend import MailerSendClient, WebhooksBuilder
ms = MailerSendClient()
request = (
WebhooksBuilder()
.domain_id("domain-id")
.build_webhooks_list_request()
)
```
### Response
(Details not provided in source)
```
--------------------------------
### Get a list of monitors
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves a paginated list of DMARC monitors configured for your account.
```APIDOC
## Get a list of monitors
### Description
Retrieves a paginated list of DMARC monitors configured for your account.
### Method
```python
ms.dmarc_monitoring.list_monitors(request)
```
### Parameters
#### Request Body (Implicitly built by DmarcMonitoringBuilder)
- **page** (int) - Optional - The page number to retrieve.
- **limit** (int) - Optional - The number of results per page.
```
--------------------------------
### Get a list of messages
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Use this to retrieve a list of all messages. Ensure the MailerSendClient is initialized.
```python
from mailersend import MailerSendClient, MessagesBuilder
ms = MailerSendClient()
request = (MessagesBuilder()
.build_list_request())
response = ms.messages.list_messages(request)
```
--------------------------------
### Error Handling Example
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Demonstrates how to handle various MailerSend API errors using try-except blocks.
```APIDOC
# Error Handling
The SDK provides comprehensive error handling with detailed error information.
```python
from mailersend import MailerSendClient
from mailersend.exceptions import MailerSendError
from mailersend import EmailBuilder
ms = MailerSendClient()
try:
email = (
EmailBuilder()
.from_email("invalid-email", "Sender") # Invalid email
.to_many([{"email": "recipient@domain.com", "name": "Recipient"}])
.subject("Test")
.html("
Test
")
.build()
)
response = ms.emails.send(email)
except MailerSendError as e:
print(f"MailerSend API Error: {e}")
print(f"Status Code: {e.status_code}")
print(f"Error Details: {e.details}")
except Exception as e:
print(f"Unexpected error: {e}")
```
Common error types:
- **ValidationError**: Invalid data in request models (handled by Pydantic)
- **AuthenticationError**: Invalid or missing API key
- **RateLimitError**: API rate limit exceeded
- **APIError**: General API errors (4xx, 5xx responses)
- **NetworkError**: Network connectivity issues
```
--------------------------------
### Initialize MailerSend Client with API Key
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/QUICK_START.md
Demonstrates the recommended way to initialize the MailerSend client using an environment variable for the API key, and contrasts it with the insecure practice of hardcoding.
```python
# Good - from environment
import os
from mailersend import MailerSendClient
ms = MailerSendClient(api_key=os.getenv("MAILERSEND_API_KEY"))
# Bad - hardcoded
ms = MailerSendClient(api_key="my-secret-key-123")
```
--------------------------------
### Get a list of invites
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves a paginated list of pending user invites. Specify page number and limit for results.
```python
from mailersend import MailerSendClient, UsersBuilder
ms = MailerSendClient()
request = (UsersBuilder()
.page(1)
.limit(25)
.build_invites_list())
response = ms.users.list_invites(request)
```
--------------------------------
### Create a Webhook
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Create a new webhook for a specified domain. Configure the URL, name, events to listen for, and whether it should be enabled by default.
```python
from mailersend import MailerSendClient
from mailersend import WebhooksBuilder
ms = MailerSendClient()
request = (
WebhooksBuilder()
.domain_id("domain-id")
.url("https://webhook.example.com")
.name("My Webhook")
.events(["activity.sent", "activity.delivered", "activity.opened"])
.enabled(True)
.build_webhook_create_request())
response = ms.webhooks.create_webhook(request)
```
--------------------------------
### Initialize MailerSendClient
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/INDEX.md
Instantiate the MailerSendClient. It's recommended to load the API key from environment variables. Alternatively, provide the API key directly during initialization.
```python
from mailersend import MailerSendClient
# From environment variable (recommended)
ms = MailerSendClient()
# Or with explicit API key
ms = MailerSendClient(api_key="your_api_key")
```
--------------------------------
### Get Domain
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/README.md
Retrieve details for a specific domain.
```APIDOC
## GET /domains/{id}
### Description
Get domain
### Method
GET
### Endpoint
/domains/{id}
```
--------------------------------
### Complete Email Sending Example
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/api-reference/email-builder.md
This snippet demonstrates how to build and send an email with multiple recipients, CC/BCC, reply-to, subject, HTML and text content, personalization, attachments, tracking, custom headers, and tags. Ensure you have initialized MailerSendClient.
```python
from mailersend import MailerSendClient, EmailBuilder
ms = MailerSendClient()
email = (EmailBuilder()
.from_email("marketing@example.com", "Marketing Team")
.to_many([
{"email": "user1@example.com", "name": "John Doe"},
{"email": "user2@example.com", "name": "Jane Smith"}
])
.cc("manager@example.com", "Manager")
.bcc([{"email": "archive@example.com", "name": "Archive"}])
.reply_to("support@example.com", "Support")
.subject("Monthly Newsletter - {$month}")
.html("Hello {$name}!
Welcome to our newsletter.
")
.text("Hello {$name}!\n\nWelcome to our newsletter.")
.personalize_many([
{"email": "user1@example.com", "data": {"name": "John", "month": "January"}},
{"email": "user2@example.com", "data": {"name": "Jane", "month": "January"}}
])
.attach_file("report.pdf")
.tag("newsletter", "monthly")
.track_opens(True)
.track_clicks(True)
.header("X-Campaign", "newsletter-jan-2024")
.build())
response = ms.emails.send(email)
print(response.id) # Message ID
```
--------------------------------
### Analytics
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Get analytics data for your email campaigns.
```APIDOC
## GET analytics
### Description
Get analytics data for your email campaigns.
### Method
GET
### Endpoint
/analytics
```
--------------------------------
### Get API Quota
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves the current API quota usage.
```APIDOC
## Get API Quota
### Description
Retrieves the current API quota usage.
### Method
```python
response = ms.api_quota.get_quota()
```
### Response
#### Success Response (200)
- **data** (object) - An object containing quota information, including limits and current usage.
```
--------------------------------
### Initialize MailerSend Client with Explicit API Key
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/api-reference/mailersend-client.md
Initialize the client by providing the API key directly as a string argument.
```python
ms = MailerSendClient(api_key="your_api_key_here")
```
--------------------------------
### Get a single webhook
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves the details of a specific webhook by its ID.
```APIDOC
## Get a single webhook
### Description
Retrieves the details of a specific webhook by its ID.
### Method
GET (inferred from get_webhook)
### Endpoint
/v1/webhooks/{webhook_id} (inferred)
### Parameters
#### Path Parameters
- **webhook_id** (string) - Required - The ID of the webhook to retrieve.
### Request Example
```python
from mailersend import MailerSendClient
from mailersend import WebhooksBuilder
ms = MailerSendClient()
request = (WebhooksBuilder()
.webhook_id("webhook-id")
.build_webhook_get_request())
response = ms.webhooks.get_webhook(request)
```
### Response
#### Success Response (200)
- **id** (string) - The unique identifier for the webhook.
- **domain_id** (string) - The ID of the associated domain.
- **url** (string) - The URL of the webhook.
- **name** (string) - The name of the webhook.
- **events** (array of strings) - The events the webhook is subscribed to.
- **enabled** (boolean) - The status of the webhook (true/false).
- **created_at** (string) - The timestamp when the webhook was created.
- **updated_at** (string) - The timestamp when the webhook was last updated.
```
--------------------------------
### Get a single webhook
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves the details of a specific webhook by its ID.
```APIDOC
## Get a single webhook
### Description
Retrieves the details of a specific webhook by its ID.
### Method
```python
ms.webhooks.get_webhook(request)
```
### Parameters
This method uses a `WebhooksBuilder` to construct the request.
- `webhook_id` (string) - Required - The ID of the webhook to retrieve.
### Request Example
```python
from mailersend import MailerSendClient, WebhooksBuilder
ms = MailerSendClient()
request = (
WebhooksBuilder()
.webhook_id("webhook-id")
.build_webhook_get_request()
)
```
### Response
(Details not provided in source)
```
--------------------------------
### Get a single template
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves the details of a specific template by its ID.
```APIDOC
## Get a single template
### Description
Retrieves the details of a specific template by its ID.
### Method
```python
ms.templates.get_template(request)
```
### Parameters
This method uses a `TemplatesBuilder` to construct the request.
- `template` (string) - Required - The ID of the template to retrieve.
### Request Example
```python
from mailersend import MailerSendClient, TemplatesBuilder
ms = MailerSendClient()
request = (
TemplatesBuilder()
.template("template-id")
.build_template_get_request()
)
```
### Response
(Details not provided in source)
```
--------------------------------
### Initialize MailerSendClient using Environment Variable
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/configuration.md
After setting the MAILERSEND_API_KEY environment variable, the MailerSendClient can be initialized without any parameters, and it will automatically read the key. This is the recommended best practice for production.
```python
from mailersend import MailerSendClient
from dotenv import load_dotenv
load_dotenv() # Loads from .env file
ms = MailerSendClient() # Auto-reads from MAILERSEND_API_KEY
```
--------------------------------
### Get a sender identity
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves details for a specific sender identity.
```APIDOC
## Get a sender identity
### Description
Retrieves details for a specific sender identity.
### Method
```python
ms.identities.get_identity(request)
```
### Parameters
This method uses an `IdentityBuilder` to construct the request.
### Request Example
```python
from mailersend import MailerSendClient, IdentityBuilder
ms = MailerSendClient()
request = (IdentityBuilder()
.identity_id("identity-id")
.build_get_request())
```
```
--------------------------------
### Create Webhook
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Creates a new webhook for a specified domain, including the URL, name, events to listen for, and whether it should be enabled.
```python
from mailersend import MailerSendClient, WebhooksBuilder
ms = MailerSendClient()
request = (WebhooksBuilder()
.domain_id("domain-id")
.url("https://yourdomain.com/webhook")
.name("My webhook")
.events(["activity.sent", "activity.delivered"])
.enabled(True)
.build_webhook_create_request())
response = ms.webhooks.create_webhook(request)
```
--------------------------------
### Get DNS Records
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves the DNS records for a specified domain.
```APIDOC
## Get DNS Records
### Description
Retrieves the DNS records for a specified domain.
### Method
```python
ms.domains.get_domain_dns_records(request)
```
### Parameters
This method uses a `DomainsBuilder` to construct the request.
### Request Example
```python
from mailersend import MailerSendClient, DomainsBuilder
ms = MailerSendClient()
request = (DomainsBuilder()
.domain_id("domain-id")
.build_dns_records_request())
```
```
--------------------------------
### Get Domain Recipients
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/endpoints.md
Retrieves a list of recipients associated with a specific domain.
```APIDOC
## Get Domain Recipients
### Description
Retrieves a list of recipients associated with a specific domain.
### Method
GET
### Endpoint
/domains/{domain_id}/recipients
### Path Parameters
- **domain_id** (string, required): Domain ID
### Response
#### Success Response (200)
- Body: JSON with recipients list
```
--------------------------------
### Authenticate using .env File
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
For development, install python-dotenv, create a .env file with your API key, and load it in your Python code. The client will then use the loaded API key.
```bash
pip install python-dotenv
```
```dotenv
# .env
MAILERSEND_API_KEY=your-api-key
```
```python
from mailersend import MailerSendClient
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Client automatically uses the loaded MAILERSEND_API_KEY
ms = MailerSendClient()
```
--------------------------------
### Get a List of Activities
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieve a list of email activities. This requires importing `datetime` and `timedelta` for date filtering if needed.
```python
from mailersend import MailerSendClient, ActivityBuilder
from datetime import datetime, timedelta
ms = MailerSendClient()
```
--------------------------------
### Initialize MailerSendClient with Direct API Key
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/configuration.md
Use this method for testing, one-off scripts, or when managing multiple API keys within the same process. It provides the highest precedence for authentication.
```python
from mailersend import MailerSendClient
ms = MailerSendClient(api_key="your_api_key_here")
```
--------------------------------
### Get a List of Webhooks
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieve all webhooks configured for a specific domain. This is useful for auditing or managing existing webhook endpoints.
```python
from mailersend import MailerSendClient
from mailersend import WebhooksBuilder
ms = MailerSendClient()
request = (
WebhooksBuilder()
.domain_id("domain-id")
.build_webhooks_list_request())
response = ms.webhooks.list_webhooks(request)
```
--------------------------------
### Get a single invite
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves details for a specific pending invite by its ID.
```python
from mailersend import MailerSendClient, UsersBuilder
ms = MailerSendClient()
request = (UsersBuilder()
.invite_id("invite-id")
.build_invite_get())
response = ms.users.get_invite(request)
```
--------------------------------
### ModelList Iteration and Access Example
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/types.md
Shows how to iterate over items in a ModelList or access specific properties like total count and individual items.
```python
for item in model_list:
print(item)
# Or access directly:
first_item = model_list[0]
total_count = model_list.total
```
--------------------------------
### Authenticate using Environment Variable
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Set your API key as a system environment variable MAILERSEND_API_KEY and initialize the client. This is the recommended authentication method.
```bash
export MAILERSEND_API_KEY="your-api-key"
```
```python
from mailersend import MailerSendClient
# Automatically uses MAILERSEND_API_KEY environment variable
ms = MailerSendClient()
```
--------------------------------
### Send email with attachment
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Demonstrates how to attach a file to an email.
```APIDOC
## Send email with attachment
### Description
Sends an email that includes one or more file attachments.
### Method
`ms.emails.send(email)`
### Parameters
- **email** (EmailBuilder object) - Required - An EmailBuilder object configured with the file attachment.
### Request Example
```python
from mailersend import MailerSendClient, EmailBuilder
ms = MailerSendClient()
email = (EmailBuilder()
.from_email("sender@domain.com", "Your Name")
.to_many([{"email": "recipient@domain.com", "name": "Recipient"}])
.subject("Email with attachment")
.html("Please find attached document
")
.attach_file("document.pdf")
.build())
response = ms.emails.send(email)
```
```
--------------------------------
### Get a list of recipients
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves a list of all recipients associated with a specific domain.
```APIDOC
## Get a list of recipients
### Description
Retrieves a list of all recipients associated with a specific domain.
### Method
```python
ms.recipients.list_recipients(request)
```
### Parameters
- **domain_id** (string) - Required - The ID of the domain for which to list recipients.
### Request Example
```python
from mailersend import MailerSendClient, RecipientsBuilder
ms = MailerSendClient()
request = (RecipientsBuilder()
.domain_id("domain-id")
.build_recipients_list_request())
response = ms.recipients.list_recipients(request)
```
### Response
Details of the response are not provided in the source.
```
--------------------------------
### Get a list of messages
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves a list of all messages sent through the MailerSend service.
```APIDOC
## Get a list of messages
### Description
Retrieves a list of all messages sent through the MailerSend service.
### Method
```python
ms.messages.list_messages(request)
```
### Parameters
This method does not take explicit parameters in the SDK call, but the `request` object is built using `MessagesBuilder`.
### Request Example
```python
from mailersend import MailerSendClient, MessagesBuilder
ms = MailerSendClient()
request = (MessagesBuilder()
.build_list_request())
response = ms.messages.list_messages(request)
```
### Response
Details of the response are not provided in the source.
```
--------------------------------
### Load Plain Text Content from File
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/api-reference/email-builder.md
Load plain text content directly from a specified file path. Ensure the file is readable.
```python
builder.text_file("path/to/your/textfile.txt")
```
--------------------------------
### Get a single inbound route
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves details for a specific inbound route.
```APIDOC
## Get a single inbound route
### Description
Retrieves details for a specific inbound route.
### Method
```python
ms.inbound.get(request)
```
### Parameters
This method uses an `InboundBuilder` to construct the request.
### Request Example
```python
from mailersend import MailerSendClient, InboundBuilder
ms = MailerSendClient()
request = (InboundBuilder()
.inbound_id("inbound-id")
.build_get_request())
```
```
--------------------------------
### Initialize MailerSend Client with Custom Timeout and Retries
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/api-reference/mailersend-client.md
Initialize the client with custom timeout and maximum retry values.
```python
ms = MailerSendClient(
timeout=60,
max_retries=5
)
```
--------------------------------
### Send a Simple Email
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/api-reference/email-resource.md
Demonstrates how to send a basic email with a subject and HTML content. Requires MailerSendClient initialization.
```python
from mailersend import MailerSendClient, EmailBuilder
ms = MailerSendClient()
email = (EmailBuilder()
.from_email("sender@example.com")
.to("recipient@example.com")
.subject("Hello World")
.html("Hello World
")
.build())
response = ms.emails.send(email)
print(f"Sent: {response.id}")
```
--------------------------------
### Get a list of inbound routes
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves a list of all inbound routes for a domain.
```APIDOC
## Get a list of inbound routes
### Description
Retrieves a list of all inbound routes for a domain.
### Method
```python
ms.inbound.list(request)
```
### Parameters
This method uses an `InboundBuilder` to construct the request.
### Request Example
```python
from mailersend import MailerSendClient, InboundBuilder
ms = MailerSendClient()
request = (InboundBuilder()
.domain_id("domain-id")
.build_list_request())
```
```
--------------------------------
### Authenticate using Direct API Key
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Initialize the MailerSend client by passing your API key directly as a parameter. Use this method if environment variables or .env files are not suitable.
```python
from mailersend import MailerSendClient
ms = MailerSendClient(api_key="your-api-key")
```
--------------------------------
### Get a list of domains
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves a paginated list of all domains associated with the account.
```APIDOC
## Get a list of domains
### Description
Retrieves a paginated list of all domains configured for the account.
### Method
`ms.domains.list_domains(request)`
### Parameters
#### Request Body
- **page** (integer) - Optional - The page number for pagination.
- **limit** (integer) - Optional - The number of results per page.
### Request Example
```python
from mailersend import MailerSendClient, DomainsBuilder
ms = MailerSendClient()
request = (
DomainsBuilder()
.page(1)
.limit(25)
.build_list_request()
)
response = ms.domains.list_domains(request)
```
### Response
#### Success Response (200)
- **data** (array) - List of domains.
- **totalPage** (integer) - Total number of pages.
- **nextPage** (string) - URL for the next page.
- **previousPage** (string) - URL for the previous page.
```
--------------------------------
### MailerSendClient Initialization
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/api-reference/mailersend-client.md
Initializes the MailerSendClient with various configuration options. The API key can be provided directly or will be read from the MAILERSEND_API_KEY environment variable.
```APIDOC
## MailerSendClient
### Description
Main client for interacting with the MailerSend API. This is the entry point for all API operations.
### Constructor
```python
MailerSendClient(
api_key: Optional[str] = None,
base_url: str = "https://api.mailersend.com/v1/",
timeout: int = 30,
max_retries: int = 3,
debug: bool = False,
logger: Optional[logging.Logger] = None
)
```
### Constructor Parameters
#### api_key
- **Type**: `str` or `None`
- **Default**: `None`
- **Description**: MailerSend API key. If not provided, reads from `MAILERSEND_API_KEY` environment variable. Raises `ValueError` if neither is available.
#### base_url
- **Type**: `str`
- **Default**: `"https://api.mailersend.com/v1/"`
- **Description**: Base URL for API requests
#### timeout
- **Type**: `int`
- **Default**: `30`
- **Description**: Request timeout in seconds
#### max_retries
- **Type**: `int`
- **Default**: `3`
- **Description**: Maximum number of automatic retries for failed requests (429, 5xx status codes)
#### debug
- **Type**: `bool`
- **Default**: `False`
- **Description**: Enable detailed debug logging for all requests/responses
#### logger
- **Type**: `logging.Logger` or `None`
- **Default**: `None`
- **Description**: Custom logger instance; if not provided, creates one automatically
### Properties
#### api_key
- **Type**: `str`
- **Description**: The API key being used for authentication
#### base_url
- **Type**: `str`
- **Description**: Base URL for API endpoints
#### timeout
- **Type**: `int`
- **Description**: Request timeout in seconds
#### debug
- **Type**: `bool`
- **Description**: Whether debug logging is enabled
#### logger
- **Type**: `logging.Logger`
- **Description**: Logger instance for this client
#### session
- **Type**: `requests.Session`
- **Description**: Underlying HTTP session with retry strategy configured
```
--------------------------------
### Get Domain DNS Records
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/endpoints.md
Retrieves the DNS records required for a specific domain.
```APIDOC
## Get Domain DNS Records
### Description
Retrieves the DNS records required for a specific domain.
### Method
GET
### Endpoint
/domains/{domain_id}/dns-records
### Path Parameters
- **domain_id** (string, required): Domain ID
### Response
#### Success Response (200)
- Body: JSON with domain DNS records
```
--------------------------------
### Send an email
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Demonstrates how to send a basic email using the EmailBuilder and MailerSendClient.
```APIDOC
## Send an email
### Description
Sends a standard email with specified sender, recipients, subject, and content.
### Method
`ms.emails.send(email)`
### Parameters
- **email** (EmailBuilder object) - Required - An EmailBuilder object configured with email details.
### Request Example
```python
from mailersend import MailerSendClient, EmailBuilder
ms = MailerSendClient()
email = (EmailBuilder()
.from_email("sender@domain.com", "Your Name")
.to_many([{"email": "recipient@domain.com", "name": "Recipient"}])
.subject("Hello from MailerSend!")
.html("Hello World!
")
.text("Hello World!")
.build())
response = ms.emails.send(email)
```
```
--------------------------------
### Get Report Sources
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves the report sources for a given DMARC monitor ID.
```APIDOC
## Get Report Sources
### Description
Retrieves the report sources for a given DMARC monitor ID.
### Method
```python
response = ms.dmarc_monitoring.get_report_sources(request)
```
### Parameters
#### Request Body
- **request** (object) - Required - An object containing the monitor ID.
### Request Example
```python
from mailersend import MailerSendClient, DmarcMonitoringBuilder
ms = MailerSendClient()
request = (DmarcMonitoringBuilder()
.monitor_id("monitor-id")
.build_report_sources_request())
```
### Response
#### Success Response (200)
- **data** (list) - A list of report sources.
- **next** (string) - The next page token for pagination.
- **prev** (string) - The previous page token for pagination.
- **total** (integer) - The total number of report sources.
```
--------------------------------
### Minimal MailerSendClient Configuration
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/configuration.md
Initializes the MailerSendClient with default settings. This is suitable for basic usage where custom configurations are not required.
```python
from mailersend import MailerSendClient
ms = MailerSendClient()
```
--------------------------------
### Get list results
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves the results of an email verification process for a specific list.
```APIDOC
## Get list results
### Description
Retrieves the results of an email verification list.
### Method
GET (assumed, based on SDK usage)
### Endpoint
/v1/email-verification/lists/{verificationListId}/results
### Parameters
#### Path Parameters
- **verificationListId** (string) - Required - The ID of the verification list whose results are to be retrieved.
### Request Example
```python
from mailersend import MailerSendClient, EmailVerificationBuilder
ms = MailerSendClient()
request = (
EmailVerificationBuilder()
.verification_list_id("list-id")
.build_results_request()
)
response = ms.email_verification.get_verification_results(request)
```
```
--------------------------------
### Create SmsPersonalization Instance
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/api-reference/sms-sending.md
Instantiates the SmsPersonalization model with a phone number and a dictionary of data for variable substitution.
```python
personalization = SmsPersonalization(
phone_number="+14155552671",
data={"name": "John", "order_id": "12345"}
)
```
--------------------------------
### Get list results
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves the results of an email verification process for a given list.
```APIDOC
## Get list results
### Description
Retrieves the results of an email verification process for a given list.
### Method
GET (inferred from get_results)
### Endpoint
/v1/email-verification/lists/{list_id}/results (inferred)
### Parameters
#### Path Parameters
- **list_id** (string) - Required - The ID of the email verification list for which to get results.
### Request Example
```python
from mailersend import MailerSendClient, EmailVerificationBuilder
ms = MailerSendClient()
request = (EmailVerificationBuilder()
.email_verification_id("list-id")
.build_results())
response = ms.email_verification.get_results(request)
```
### Response
#### Success Response (200)
- **data** (array) - A list of verification results for each email.
- Each object contains:
- **email** (string) - The email address that was verified.
- **status** (string) - The verification status (e.g., "valid", "invalid", "unknown").
- **score** (number) - A score indicating the deliverability of the email.
```
--------------------------------
### Create a Webhook
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Creates a new webhook for a specified domain, including its URL, name, and subscribed events.
```APIDOC
## Create a Webhook
### Description
Creates a new webhook for a specified domain, including its URL, name, and subscribed events.
### Method
POST (inferred from create_webhook)
### Endpoint
/v1/webhooks (inferred)
### Parameters
#### Request Body
- **domain_id** (string) - Required - The ID of the domain for which to create the webhook.
- **url** (string) - Required - The URL to which webhook events will be sent.
- **name** (string) - Required - The name of the webhook.
- **events** (array of strings) - Required - A list of events to subscribe to (e.g., "activity.sent").
- **enabled** (boolean) - Required - Set to `True` to create an enabled webhook.
### Request Example
```python
from mailersend import MailerSendClient
from mailersend import WebhooksBuilder
ms = MailerSendClient()
request = (WebhooksBuilder()
.domain_id("domain-id")
.url("https://webhook.example.com")
.name("My Webhook")
.events(["activity.sent", "activity.delivered", "activity.opened"])
.enabled(True)
.build_webhook_create_request())
response = ms.webhooks.create_webhook(request)
```
### Response
#### Success Response (200)
- **id** (string) - The unique identifier for the created webhook.
- **domain_id** (string) - The ID of the associated domain.
- **url** (string) - The URL of the webhook.
- **name** (string) - The name of the webhook.
- **events** (array of strings) - The events the webhook is subscribed to.
- **enabled** (boolean) - The status of the webhook (true/false).
- **created_at** (string) - The timestamp when the webhook was created.
- **updated_at** (string) - The timestamp when the webhook was last updated.
```
--------------------------------
### MailerSendClient Constructor
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/api-reference/mailersend-client.md
Initializes the MailerSendClient. It can accept an API key directly or read it from the MAILERSEND_API_KEY environment variable. Configure base URL, timeout, retry attempts, and debug logging as needed.
```python
class MailerSendClient:
def __init__(
self,
api_key: Optional[str] = None,
base_url: str = "https://api.mailersend.com/v1/",
timeout: int = 30,
max_retries: int = 3,
debug: bool = False,
logger: Optional[logging.Logger] = None
) -> None:
```
--------------------------------
### Get recipients from unsubscribes
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves a list of recipients who have unsubscribed from emails for a specific domain.
```APIDOC
## Get recipients from unsubscribes
### Description
Retrieves a list of recipients who have unsubscribed from emails for a specific domain.
### Method
```python
ms.recipients.list_unsubscribes(request)
```
### Parameters
- **domain_id** (string) - Required - The ID of the domain for which to retrieve unsubscribes.
### Request Example
```python
from mailersend import MailerSendClient, RecipientsBuilder
ms = MailerSendClient()
request = (RecipientsBuilder()
.domain_id("domain-id")
.build_suppression_list_request())
response = ms.recipients.list_unsubscribes(request)
```
### Response
Details of the response are not provided in the source.
```
--------------------------------
### Create Webhook
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/endpoints.md
Creates a new webhook for a specified domain, with configurable URL, name, events, and enabled status.
```APIDOC
## Create Webhook
### Description
Creates a new webhook for a specified domain, with configurable URL, name, events, and enabled status.
### Method
POST
### Endpoint
/webhooks
### Request Body
- **domain_id** (string) - Required - Domain ID
- **url** (string) - Required - Webhook URL
- **name** (string) - Required - Webhook name
- **events** (string[]) - Required - Event types to subscribe to
- **enabled** (boolean) - Optional - Enable webhook (default=true)
```
--------------------------------
### Get recipients from a blocklist
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves a list of recipients who have been added to the blocklist for a specific domain.
```APIDOC
## Get recipients from a blocklist
### Description
Retrieves a list of recipients who have been added to the blocklist for a specific domain.
### Method
```python
ms.recipients.list_blocklist(request)
```
### Parameters
- **domain_id** (string) - Required - The ID of the domain for which to retrieve the blocklist.
### Request Example
```python
from mailersend import MailerSendClient, RecipientsBuilder
ms = MailerSendClient()
request = (RecipientsBuilder()
.domain_id("domain-id")
.build_suppression_list_request())
response = ms.recipients.list_blocklist(request)
```
### Response
Details of the response are not provided in the source.
```
--------------------------------
### Initialize SmsSendingBuilder
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/api-reference/sms-sending.md
Instantiate the builder for constructing SMS requests.
```python
builder = SmsSendingBuilder()
```
--------------------------------
### Get a list of scheduled messages
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves a list of all messages that have been scheduled for future delivery.
```APIDOC
## Get a list of scheduled messages
### Description
Retrieves a list of all messages that have been scheduled for future delivery.
### Method
```python
ms.schedules.list_schedules(request)
```
### Parameters
- **domain_id** (string) - Required - The ID of the domain associated with the scheduled messages.
### Request Example
```python
from mailersend import MailerSendClient, SchedulesBuilder
ms = MailerSendClient()
request = (SchedulesBuilder()
.domain_id("domain-id")
.build_list_request())
response = ms.schedules.list_schedules(request)
```
### Response
Details of the response are not provided in the source.
```
--------------------------------
### Get Opens by Reading Environment
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieve email open analytics data based on the reading environment. Ensure MailerSendClient and AnalyticsBuilder are initialized.
```python
from mailersend import MailerSendClient, AnalyticsBuilder
ms = MailerSendClient()
request = (
AnalyticsBuilder()
.date_from(date_from)
.date_to(date_to)
.domain_id("domain-id")
.build()
)
response = ms.analytics.get_opens_by_reading_environment(request)
```
--------------------------------
### Configure Custom Python Logging
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/configuration.md
Set up a custom logging configuration using a dictionary to control formatters, handlers, and specific logger levels. This allows for detailed control over log output, including file logging.
```python
import logging
from mailersend import MailerSendClient
# Configure logging before creating client
config = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"verbose": {
"format": "% (asctime)s - % (name)s - % (levelname)s - % (message)s"
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"level": "DEBUG",
"formatter": "verbose",
"stream": "ext://sys.stdout"
},
"file": {
"class": "logging.FileHandler",
"level": "INFO",
"formatter": "verbose",
"filename": "mailersend.log"
}
},
"loggers": {
"mailersend": {
"level": "DEBUG",
"handlers": ["console", "file"]
}
}
}
import logging.config
logging.config.dictConfig(config)
ms = MailerSendClient()
```
--------------------------------
### Get a list of sender identities
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves a list of all sender identities associated with a domain.
```APIDOC
## Get a list of sender identities
### Description
Retrieves a list of all sender identities associated with a domain.
### Method
```python
ms.identities.list_identities(request)
```
### Parameters
This method uses an `IdentityBuilder` to construct the request.
### Request Example
```python
from mailersend import MailerSendClient, IdentityBuilder
ms = MailerSendClient()
request = (IdentityBuilder()
.domain_id("domain-id")
.build_list_request())
```
```
--------------------------------
### Invite a user to account
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Invites a new user to the account. Supports basic invites with admin roles or custom invites with specific permissions, roles, and domain/template associations. Requires the user's email address.
```python
from mailersend import MailerSendClient, UsersBuilder
ms = MailerSendClient()
# Basic invite with admin role
request = (UsersBuilder()
.email("newuser@example.com")
.admin_role()
.build_user_invite())
response = ms.users.invite_user(request)
# Custom invite with specific permissions and access
request = (UsersBuilder()
.email("designer@example.com")
.designer_role()
.add_permission("read-all-templates")
.add_permission("manage-template")
.add_template("template-id")
.add_domain("domain-id")
.requires_periodic_password_change(True)
.build_user_invite())
response = ms.users.invite_user(request)
```
--------------------------------
### Safe Response Data Access with Defaults
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Use the `get()` method for safe access to response data, providing default values to prevent errors when keys are missing. This is useful for handling potentially absent fields.
```python
# Safe access with defaults
recipient_id = response.get("data", {}).get("id", "unknown")
error_message = response.get("error", "No error")
# Safe nested access
meta_info = response.get("meta", {})
total_count = meta_info.get("total", 0)
current_page = meta_info.get("page", 1)
```
--------------------------------
### Get a single domain
Source: https://github.com/mailersend/mailersend-python/blob/main/README.md
Retrieves details for a specific domain using its unique ID.
```APIDOC
## Get a single domain
### Description
Retrieves the details of a specific domain by its ID.
### Method
`ms.domains.get_domain(request)`
### Parameters
#### Request Body
- **domain_id** (string) - Required - The ID of the domain to retrieve.
### Request Example
```python
from mailersend import MailerSendClient, DomainsBuilder
ms = MailerSendClient()
request = (
DomainsBuilder()
.domain_id("domain-id")
.build_get_request()
)
response = ms.domains.get_domain(request)
```
### Response
#### Success Response (200)
- **id** (string) - The domain ID.
- **name** (string) - The domain name.
- **status** (string) - The status of the domain (e.g., 'active', 'pending_verification').
- **verified** (boolean) - Indicates if the domain is verified.
```
--------------------------------
### Send Email with Advanced Tracking Options
Source: https://github.com/mailersend/mailersend-python/blob/main/_autodocs/api-reference/email-resource.md
Shows how to enable advanced tracking features like open tracking, click tracking, and content tracking, as well as adding custom tags and headers.
```python
from mailersend import MailerSendClient, EmailBuilder
ms = MailerSendClient()
email = (EmailBuilder()
.from_email("sender@example.com")
.to("recipient@example.com")
.subject("Campaign Email")
.html("Campaign
")
.track_opens(True)
.track_clicks(True)
.track_content(True)
.tag("campaign", "2024-01")
.header("X-Campaign-ID", "campaign-2024-01")
.build())
response = ms.emails.send(email)
```