### Install content-types Source: https://github.com/mikeckennedy/listmonk/blob/main/dev-docs/package-guides/content-types_reference.md Install the library using pip or uv. The CLI tool can be installed standalone. ```bash pip install content-types ``` ```bash uv add content-types ``` ```bash uv tool install content-types ``` ```bash pipx install content-types ``` -------------------------------- ### Running the Example Client Source: https://github.com/mikeckennedy/listmonk/blob/main/GEMINI.md Execute the example client script to demonstrate major API operations against a real Listmonk instance. ```bash python example_client/client.py ``` -------------------------------- ### Install Tenacity Source: https://github.com/mikeckennedy/listmonk/blob/main/dev-docs/package-guides/tenacity_reference.md Install the Tenacity library using pip. ```bash pip install tenacity ``` -------------------------------- ### Basic HTTPX Usage Examples Source: https://github.com/mikeckennedy/listmonk/blob/main/dev-docs/package-guides/httpx_reference.md Provides examples of common HTTPX operations, including simple GET requests, POST requests with JSON or form data, custom headers, query parameters, and following redirects. ```python import httpx # Simple GET response = httpx.get("https://httpbin.org/get") print(response.status_code) # 200 print(response.json()) # POST with JSON body response = httpx.post("https://httpbin.org/post", json={"key": "value"}) # POST with form data response = httpx.post("https://httpbin.org/post", data={"key": "value"}) # Custom headers response = httpx.get("https://example.com", headers={"Authorization": "Bearer token123"}) # Query parameters response = httpx.get("https://httpbin.org/get", params={"page": 1, "limit": 10}) # Follow redirects (disabled by default) response = httpx.get("http://github.com", follow_redirects=True) ``` -------------------------------- ### Basic httpx Usage Example Source: https://github.com/mikeckennedy/listmonk/blob/main/dev-docs/package-guides/httpx_reference.md Demonstrates making a GET request and accessing basic response properties like status code, success status, text content, raw bytes, and JSON parsing. ```python import httpx response = httpx.get("https://httpbin.org/get") # Status print(response.status_code) # 200 print(response.is_success) # True # Body access print(response.text) # decoded string print(response.content) # raw bytes print(response.json()) # parsed JSON # Chaining with raise_for_status data = httpx.get("https://api.example.com/data").raise_for_status().json() # Redirect info response = httpx.get("http://github.com/") print(response.status_code) # 301 print(response.next_request) # response = httpx.get("http://github.com/", follow_redirects=True) print(response.history) # [>> import listmonk >>> listmonk.set_url_base('https://listmonk.somedomain.tech') >>> listmonk.login('admin', 'super-secret') ``` -------------------------------- ### Basic Client Usage Source: https://github.com/mikeckennedy/listmonk/blob/main/dev-docs/package-guides/httpx_reference.md Demonstrates the recommended way to use the httpx client as a context manager for automatic resource management. ```python import httpx # Recommended: use as context manager with httpx.Client() as client: response = client.get("https://example.com") ``` -------------------------------- ### Instantiate CampaignPreview Source: https://github.com/mikeckennedy/listmonk/blob/main/docs/reference/models.CampaignPreview.md Shows how to create an instance of the CampaignPreview model. This is typically used when you need to represent a campaign's rendered output. ```python models.CampaignPreview() ``` -------------------------------- ### Client with Default Headers and Auth Source: https://github.com/mikeckennedy/listmonk/blob/main/dev-docs/package-guides/httpx_reference.md Illustrates setting default headers and authentication for all requests made by the client instance. ```python with httpx.Client( headers={"User-Agent": "my-app/1.0"}, auth=("username", "password"), ) as client: response = client.get("https://example.com/protected") ``` -------------------------------- ### Get Subscribers Source: https://github.com/mikeckennedy/listmonk/blob/main/dev-docs/package-guides/listmonk_reference.md Retrieves a list of subscribers with options for filtering, sorting, and pagination. ```APIDOC ## GET /api/subscribers ### Description Retrieves a list of subscribers with options for filtering, sorting, and pagination. ### Method GET ### Endpoint /api/subscribers ### Parameters #### Query Parameters - **query** (string) - Optional - SQL expression for subscriber search - **list_id** (int[]) - Optional - List IDs to filter by (repeat for multiple) - **subscription_status** (string) - Optional - Filter by subscription status when `list_id` is set - **order_by** (string) - Optional - Sort field: `name`, `status`, `created_at`, `updated_at` - **order** (string) - Optional - `ASC` or `DESC` - **page** (number) - Optional - Page number - **per_page** (number) - Optional - Results per page (use `'all'` for everything) ### Request Example ```shell curl -u 'user:token' 'http://localhost:9000/api/subscribers?page=1&per_page=100' ``` ### Response #### Success Response (200) - **data** (object) - Contains subscriber results and pagination info - **results** (array) - Array of subscriber objects - **query** (string) - The query used for filtering - **total** (number) - Total number of subscribers - **per_page** (number) - Number of subscribers per page - **page** (number) - Current page number #### Response Example ```json { "data": { "results": [ { "id": 1, "created_at": "2020-02-10T23:07:16.199433+01:00", "updated_at": "2020-02-10T23:07:16.199433+01:00", "uuid": "ea06b2e7-4b08-4697-bcfc-2a5c6dde8f1c", "email": "john@example.com", "name": "John Doe", "attribs": { "city": "Bengaluru", "good": true, "type": "known" }, "status": "enabled", "lists": [ { "subscription_status": "unconfirmed", "id": 1, "uuid": "ce13e971-...", "name": "Default list", "type": "public", "tags": ["test"], "created_at": "2020-02-10T23:07:16.194843+01:00", "updated_at": "2020-02-10T23:07:16.194843+01:00" } ] } ], "query": "", "total": 3, "per_page": 20, "page": 1 } } ``` ``` -------------------------------- ### Update Subscriber Information Source: https://github.com/mikeckennedy/listmonk/blob/main/docs/reference/create_subscriber.html Example of updating an existing subscriber's information via the CLI. ```bash listmonk cli subscriber update --id 1 --name "Updated Name" ``` -------------------------------- ### Create a New Template Source: https://github.com/mikeckennedy/listmonk/blob/main/docs/reference/create_subscriber.html Demonstrates creating a new email template using the Listmonk CLI. ```bash listmonk cli template create --name "My Template" --content "

Hello {{.Name}}

" ``` -------------------------------- ### Get Subscribers with Pagination Source: https://github.com/mikeckennedy/listmonk/blob/main/dev-docs/package-guides/listmonk_reference.md Retrieve a paginated list of subscribers. Use `per_page='all'` to fetch all subscribers. ```shell # All subscribers, paginated curl -u 'user:token' 'http://localhost:9000/api/subscribers?page=1&per_page=100' ``` -------------------------------- ### Instantiate Campaign Model Source: https://github.com/mikeckennedy/listmonk/blob/main/docs/reference/models.Campaign.md Shows how to create a new Campaign object. This is a basic instantiation and does not include any specific attributes. ```python models.Campaign() ``` -------------------------------- ### Create a New Subscriber Source: https://github.com/mikeckennedy/listmonk/blob/main/docs/reference/create_subscriber.html Demonstrates how to create a new subscriber using the Listmonk CLI. ```bash listmonk cli subscriber create --list-id 1 --email "test@example.com" --name "Test User" ``` -------------------------------- ### Get All Templates Source: https://github.com/mikeckennedy/listmonk/blob/main/dev-docs/package-guides/listmonk_reference.md Retrieves a list of all available templates. Useful for iterating through and displaying template information. ```python all_templates = listmonk.templates() for t in all_templates: print(f'{t.name} (type: {t.type}, default: {t.is_default})') ``` -------------------------------- ### Get Subscriber by UUID Source: https://github.com/mikeckennedy/listmonk/blob/main/docs/reference/subscriber_by_uuid.html Retrieves a specific subscriber's details using their unique UUID. ```APIDOC ## subscriber_by_uuid() ### Description Retrieves a subscriber's information using their unique UUID. ### Method GET ### Endpoint `/subscribers/{uuid}` ### Parameters #### Path Parameters - **uuid** (string) - Required - The unique identifier of the subscriber. ### Response #### Success Response (200) - **uuid** (string) - The unique identifier of the subscriber. - **email** (string) - The email address of the subscriber. - **name** (string) - The name of the subscriber. - **status** (string) - The current status of the subscriber (e.g., 'subscribed', 'unsubscribed'). - **created_at** (string) - The timestamp when the subscriber was created. - **updated_at** (string) - The timestamp when the subscriber was last updated. #### Response Example { "uuid": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "email": "test@example.com", "name": "Test User", "status": "subscribed", "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:00:00Z" } ``` -------------------------------- ### Configure Database Connection Source: https://github.com/mikeckennedy/listmonk/blob/main/docs/reference/create_subscriber.html Shows how to configure the database connection for Listmonk using environment variables. ```bash export DB_DIALECT=postgres export DB_HOST=localhost export DB_PORT=5432 export DB_USER=listmonk export DB_PASSWORD=secret export DB_NAME=listmonk ``` -------------------------------- ### Get Subscriber by ID Source: https://github.com/mikeckennedy/listmonk/blob/main/docs/reference/subscriber_by_id.html Retrieves a single subscriber's details using their unique ID. ```APIDOC ## GET /subscribers/{id} ### Description Retrieves a single subscriber's details using their unique ID. ### Method GET ### Endpoint /subscribers/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the subscriber. ``` -------------------------------- ### Get Subscriber Details Source: https://github.com/mikeckennedy/listmonk/blob/main/docs/reference/create_subscriber.html Shows how to retrieve details for a specific subscriber using the Listmonk CLI. ```bash listmonk cli subscriber get --id 1 ``` -------------------------------- ### Retrieve Subscribers by List Source: https://github.com/mikeckennedy/listmonk/blob/main/docs/index.html Get a list of subscribers associated with a specific mailing list ID. ```python ## Various ways to access existing subscribers subscribers: list[Subscriber] = listmonk.subscribers(list_id=9) ``` -------------------------------- ### Manage Campaigns Source: https://github.com/mikeckennedy/listmonk/blob/main/README.md Examples for retrieving, creating, updating, and deleting email campaigns using the Listmonk API. ```python # Access existing campaigns from listmonk.models import Campaign from datetime import datetime, timedelta campaigns: list[Campaign] = listmonk.campaigns() campaign: Optional[Campaign] = listmonk.campaign_by_id(15) # Upload media and create a campaign with attachments media = listmonk.upload_media(pathlib.Path("/path/to/report.pdf")) # Or upload from bytes: media = listmonk.upload_media(pdf_bytes, filename="report.pdf") listmonk.create_campaign(name='This is my Great Campaign!', subject="You won't believe this!", body='

Some Insane HTML!

', # Optional alt_body='Some Insane TXT!', # Optional send_at=datetime.now() + timedelta(hours=1), # Optional template_id=5, # Optional; defaults to None (server uses its default template) list_ids={1, 2}, # Optional Defaults to 1 tags=['good', 'better', 'best'], # Optional media_ids=[media.id], # Optional, attach uploaded media ) # Update A Campaign campaign_to_update: Optional[Campaign] = listmonk.campaign_by_id(15) campaign_to_update.name = "More Elegant Name" campaign_to_update.subject = "Even More Clickbait!!" campaign_to_update.body = "

There's a lot more we need to say so we're updating this programmatically!" campaign_to_update.altbody = "There's a lot more we need to say so we're updating this programmatically!" campaign_to_update.lists = [3, 4] # Existing attachments are kept on update; pass media_ids=[...] to change them # (or media_ids=[] to remove them all). listmonk.update_campaign(campaign_to_update) # Delete a Campaign (by its numeric ID) listmonk.delete_campaign(15) # Preview Campaign preview = listmonk.campaign_preview_by_id(15) print(preview.preview) ``` -------------------------------- ### Tornado Coroutine Support Source: https://github.com/mikeckennedy/listmonk/blob/main/dev-docs/package-guides/tenacity_reference.md Demonstrates how Tenacity automatically detects and supports Tornado coroutines when the Tornado library is installed. ```APIDOC ## Tornado Support When `tornado` is installed, `@retry` auto-detects Tornado coroutines: ```python @retry async def my_tornado_handler(http_client, url): await http_client.fetch(url) ``` The `TornadoRetrying` class uses `tornado.gen.sleep` by default. ``` -------------------------------- ### Initialize Bibliography Reference Tooltips Source: https://github.com/mikeckennedy/listmonk/blob/main/docs/reference/subscriber_by_email.html Iterates through bibliography references, finds associated citation information, and sets up tooltips using tippy.js for displaying citation details. ```javascript var bibliorefs = window.document.querySelectorAll('a[role="doc-biblioref"]'); for (var i=0; i None ``` ``` -------------------------------- ### Sending Pre-Built Requests Source: https://github.com/mikeckennedy/listmonk/blob/main/dev-docs/package-guides/httpx_reference.md Illustrates how to build a request object and then send it using an httpx client. ```APIDOC ## Sending Pre-Built Requests ### Description Create a `Request` object manually, inspect or modify it, and then send it using a client's `send` method. ### Code Example ```python import httpx with httpx.Client(headers={"X-Api-Key": "secret"}) as client: request = client.build_request("GET", "https://api.example.com") # Inspect or modify before sending print(request.headers) response = client.send(request) ``` ``` -------------------------------- ### Get All Mailing Lists Source: https://github.com/mikeckennedy/listmonk/blob/main/docs/reference/lists.md Retrieves all mailing lists from the server in a single request. Optional per-request timeout can be configured. ```python lists(timeout_config=None) ``` -------------------------------- ### Create a New Campaign Source: https://github.com/mikeckennedy/listmonk/blob/main/docs/reference/create_subscriber.html This snippet demonstrates creating a new email campaign using the Listmonk CLI. ```bash listmonk cli campaign create --from "sender@example.com" --subject "Hello World" --body "This is a test email." --list-ids 1 ``` -------------------------------- ### Custom JSON Schema Generator Source: https://github.com/mikeckennedy/listmonk/blob/main/dev-docs/package-guides/pydantic_reference.md Extend GenerateJsonSchema to customize the generated JSON schema, for example, by adding a custom '$id'. ```python from pydantic.json_schema import GenerateJsonSchema class MyGenerator(GenerateJsonSchema): def generate(self, schema, mode='validation'): json_schema = super().generate(schema, mode=mode) json_schema['$id'] = 'my-custom-id' return json_schema schema = Model.model_json_schema(schema_generator=MyGenerator) ``` -------------------------------- ### Client with Base URL Source: https://github.com/mikeckennedy/listmonk/blob/main/dev-docs/package-guides/httpx_reference.md Shows how to configure a base URL for the client, simplifying requests to a specific API endpoint. ```python with httpx.Client(base_url="https://api.example.com/v1") as client: response = client.get("/users") # GET https://api.example.com/v1/users ``` -------------------------------- ### Media API - Get a specific media file Source: https://github.com/mikeckennedy/listmonk/blob/main/dev-docs/package-guides/listmonk_reference.md Retrieve details for a specific uploaded media file using its ID. ```APIDOC ## GET /api/media/{id} ### Description Retrieve details for a specific uploaded media file using its ID. ### Method GET ### Endpoint `/api/media/{id}` ### Parameters #### Path Parameters - **id** (number) - Required - The ID of the media file to retrieve. ``` -------------------------------- ### Get Subscribers Filtered by List ID Source: https://github.com/mikeckennedy/listmonk/blob/main/dev-docs/package-guides/listmonk_reference.md Retrieve subscribers belonging to specific lists by providing multiple `list_id` parameters. ```shell # Filter by list curl -u 'user:token' 'http://localhost:9000/api/subscribers?list_id=1&list_id=2&page=1&per_page=100' ``` -------------------------------- ### Upload Media and Create Campaign with Attachments Source: https://github.com/mikeckennedy/listmonk/blob/main/docs/index.html Uploads a PDF file as media and then creates a new campaign, attaching the uploaded media. Alternatively, media can be uploaded directly from bytes. ```python media = listmonk.upload_media(pathlib.Path("/path/to/report.pdf")) ## Or upload from bytes: media = listmonk.upload_media(pdf_bytes, filename="report.pdf") listmonk.create_campaign(name='This is my Great Campaign!', subject="You won't believe this!", body='

Some Insane HTML!

', # Optional alt_body='Some Insane TXT!', # Optional send_at=datetime.now() + timedelta(hours=1), # Optional template_id=5, # Optional; defaults to None (server uses its default template) list_ids={1, 2}, # Optional Defaults to 1 tags=['good', 'better', 'best'], # Optional media_ids=[media.id], # Optional, attach uploaded media ) ``` -------------------------------- ### Call template_preview_by_id() Source: https://github.com/mikeckennedy/listmonk/blob/main/docs/reference/template_preview_by_id.md Use this function to get an HTML preview of a specific template. The preview is generated server-side with sample data. ```python template_preview_by_id( template_id, timeout_config=None, ) ``` -------------------------------- ### Initialize and Authenticate Listmonk Client Source: https://github.com/mikeckennedy/listmonk/blob/main/README.md Set the base URL for your Listmonk instance and log in using your credentials. Verify the login status to ensure connectivity. ```python import pathlib import listmonk from listmonk.models import MailingList, Subscriber from typing import Optional listmonk.set_url_base('https://yourlistmonkurl.com') listmonk.login('sammy_z', '1234') valid: bool = listmonk.verify_login() # Is it alive and working? up: bool = listmonk.is_healthy() ``` -------------------------------- ### Get Campaign Preview by ID Source: https://github.com/mikeckennedy/listmonk/blob/main/docs/llms-full.txt Fetches the rendered preview of a campaign, including its HTML body, identified by its campaign ID. ```APIDOC ## GET /campaigns/{campaign_id}/preview ### Description Get the rendered preview of a campaign with the given ID. ### Method GET ### Endpoint /campaigns/{campaign_id}/preview ### Parameters #### Path Parameters - **campaign_id** (int) - Required - The numeric ID of the campaign to preview, e.g. 7. #### Query Parameters - **timeout_config** (httpx2.Timeout | None) - Optional - Per-request timeout; defaults to 10 seconds. ### Response #### Success Response (200) - **campaign_preview** (listmonk.models.CampaignPreview) - A CampaignPreview object whose ``preview`` attribute holds the rendered HTML body returned by the server. #### Response Example { "preview": "

Rendered HTML Content

" } ``` -------------------------------- ### Instantiate TemplatePreview Source: https://github.com/mikeckennedy/listmonk/blob/main/docs/reference/models.TemplatePreview.md Instantiate the TemplatePreview model. The `preview` attribute will contain the rendered HTML. ```python models.TemplatePreview() ``` -------------------------------- ### Get List by ID Source: https://github.com/mikeckennedy/listmonk/blob/main/docs/reference/list_by_id.html Fetches a single mailing list by its ID. This is a fundamental operation for retrieving details of a specific list. ```APIDOC ## GET /lists/{id} ### Description Retrieves a specific mailing list using its unique identifier. ### Method GET ### Endpoint /lists/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the mailing list to retrieve. ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the list. - **uuid** (string) - The universally unique identifier of the list. - **name** (string) - The name of the mailing list. - **description** (string) - A description of the mailing list. - **created_at** (string) - The timestamp when the list was created. - **updated_at** (string) - The timestamp when the list was last updated. - **subscriber_count** (integer) - The number of subscribers in the list. - **public** (boolean) - Indicates if the list is public. - **allow_ பதிவு** (boolean) - Indicates if new subscriptions are allowed. #### Response Example ```json { "id": 1, "uuid": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "name": "Newsletter Subscribers", "description": "Main list for general newsletter subscribers.", "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:00:00Z", "subscriber_count": 1500, "public": true, "allow_ பதிவு": true } ``` ``` -------------------------------- ### TypeAdapter Get Default Value Source: https://github.com/mikeckennedy/listmonk/blob/main/dev-docs/package-guides/pydantic_reference.md Method to retrieve the default value for a type managed by TypeAdapter, considering strictness and context. ```python def get_default_value( self, *, strict: bool | None = None, context: Any | None = None, ) -> Some[T] | None: ... ``` -------------------------------- ### Built-in Pydantic Alias Generators Source: https://github.com/mikeckennedy/listmonk/blob/main/dev-docs/package-guides/pydantic_reference.md Examples of Pydantic's built-in alias generator functions for converting between snake_case, camelCase, and PascalCase. ```python from pydantic.alias_generators import to_pascal, to_camel, to_snake to_pascal('user_name') # 'UserName' to_camel('user_name') # 'userName' to_snake('UserName') # 'user_name' to_snake('camelCase') # 'camel_case' to_snake('kebab-case') # 'kebab_case' ``` -------------------------------- ### Initialize Bibliographical Reference Tooltips Source: https://github.com/mikeckennedy/listmonk/blob/main/docs/reference/campaigns.html Iterates through all document bibliographical reference links ('a[role="doc-biblioref"]'). For each link, it finds associated citation information and sets up a tooltip using tippyHover to display the citation entry. ```javascript var bibliorefs = window.document.querySelectorAll('a[role="doc-biblioref"]'); for (var i=0; i