### Setup Python Virtual Environment and Run Tests (Shell) Source: https://github.com/campaignmonitor/createsend-python/blob/master/README.md Provides shell commands to set up a Python virtual environment, install dependencies, configure the Python path, and run pytest for the project's unit tests. Includes commands for activating/deactivating the environment. ```Shell > python -m venv venv > source venv/bin/activate # On Windows, use: venv\Scripts\activate > pip install pytest > export PYTHONPATH=$(pwd)/lib # on Windows: set PYTHONPATH=%cd%\lib > pytest > # To run a specific test file > pytest test/test_administrator.py To deactivate the virtual environment run: > deactivate ``` -------------------------------- ### Install createsend library Source: https://github.com/campaignmonitor/createsend-python/blob/master/README.md Command to install the createsend package via pip. ```bash pip install createsend ``` -------------------------------- ### Send Classic Emails with Attachments using Python Source: https://context7.com/campaignmonitor/createsend-python/llms.txt This code example shows how to send a classic email with custom HTML content, plain text, and attachments, including a PDF, using the createsend-python library. It also demonstrates how to retrieve classic email groups. ```python import base64 from createsend import Transactional auth = {'api_key': 'your_api_key'} tx = Transactional(auth) # Send a classic email with custom HTML with open("invoice.pdf", "rb") as f: pdf_content = base64.b64encode(f.read()).decode() result = tx.classic_email_send( subject="Your Invoice #12345", from_address="billing@example.com", to=["customer@example.com"], consent_to_track="Yes", html="
Thank you for your order!
", text="Invoice #12345\n\nThank you for your order!", attachments=[ { "Content": pdf_content, "Name": "invoice.pdf", "Type": "application/pdf" } ], track_opens=True, track_clicks=True, inline_css=True, group="invoices" ) # Get classic email groups groups = tx.classic_email_groups() for group in groups: print(f"Group: {group.Group}") ``` -------------------------------- ### GET /clients Source: https://github.com/campaignmonitor/createsend-python/blob/master/README.md Retrieves a list of all clients associated with the authenticated account. ```APIDOC ## GET /clients ### Description Retrieves a list of all clients for the authenticated user. ### Method GET ### Response #### Success Response (200) - **clients** (array) - A list of client objects containing ClientID and Name. ``` -------------------------------- ### Add Subscriber with Custom Fields Unit Test (Python) Source: https://github.com/campaignmonitor/createsend-python/blob/master/README.md A unit test example demonstrating how to add a subscriber to a list with custom fields. It uses stubbed requests to simulate API responses and asserts the returned email address. ```Python def test_add_with_custom_fields(self): self.subscriber.stub_request("subscribers/%s.json" % self.list_id, "add_subscriber.json") custom_fields = [ { "Key": 'website', "Value": 'https://example.com/' } ] email_address = self.subscriber.add(self.list_id, "subscriber@example.com", "Subscriber", custom_fields, True) self.assertEqual(email_address, "subscriber@example.com") ``` -------------------------------- ### Run Automated Tests with Tox (Shell) Source: https://github.com/campaignmonitor/createsend-python/blob/master/README.md Shell commands to install tox and run automated tests across different Python versions using tox. Tox is a tool for automating testing in Python. ```Shell > pip install tox > tox ``` -------------------------------- ### GET /campaigns/{id}/summary Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Retrieves comprehensive performance metrics for a specific campaign, including opens, clicks, and bounces. ```APIDOC ## GET /campaigns/{id}/summary ### Description Fetches a summary of campaign performance metrics. ### Method GET ### Endpoint /campaigns/{id}/summary ### Parameters #### Path Parameters - **id** (string) - Required - The unique campaign ID ### Response #### Success Response (200) - **TotalOpened** (int) - Total number of opens - **Clicks** (int) - Total number of clicks - **Bounced** (int) - Total number of bounces - **Unsubscribed** (int) - Total number of unsubscribes ``` -------------------------------- ### Get Transactional Message Details and Timeline (Python) Source: https://github.com/campaignmonitor/createsend-python/blob/master/README.md Demonstrates how to retrieve details of a specific transactional message using its ID and how to count bounced emails from the message timeline. It requires API key and message ID to be set as environment variables. ```Python from createsend import Transactional import os import sys auth = {'api_key': os.getenv('CREATESEND_API_KEY', '')} msg_id = os.getenv('MESSAGE_ID', '') if len(auth) == 0: print("API Key Not Provided") sys.exit(1) if len(msg_id) == 0: print("Message ID Not Provided") sys.exit(1) #auth = {'api_key': '[api_key]'} #msg_id = "[message id]" # e.g., becd8473-6a19-1feb-84c5-28d16948a5fc tx = Transactional(auth) # Get message details using message id. # We can optionally disable loading the body by setting exclude_message_body to `True`. msg_details = tx.message_details(msg_id, statistics=False, exclude_message_body=True) print(f'smart email id: {msg_details.SmartEmailID}') print(f'bounce type: {msg_details.BounceType}') print(f'bounce category: {msg_details.BounceCategory}') print(f'html: {msg_details.Message.Body.Html}') print('--') # Count the number of bounced mail using message timeline msg_timeline = tx.message_timeline() num_bounced = 0 for m in msg_timeline: print('--') print(f'message id: {m.MessageID}') if str.lower(m.Status) == 'bounced': num_bounced += 1 print(f'bounce type: {m.BounceType}') print(f'bounce category: {m.BounceCategory}') print('--') print(f"total bounces: {num_bounced}") ``` -------------------------------- ### OAuth Authorization Flow Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Guides through the process of generating authorization URLs and exchanging authorization codes for access tokens to implement the full OAuth flow. ```APIDOC ## OAuth Authorization Flow Generate authorization URLs and exchange authorization codes for access tokens to implement the full OAuth flow in your application. ```python from createsend import CreateSend cs = CreateSend() # Step 1: Generate authorization URL for user redirect authorize_url = cs.authorize_url( client_id='your_client_id', redirect_uri='https://yourapp.com/oauth/callback', scope='ManageLists,ImportSubscribers,SendCampaigns', state='optional_state_data' ) print(f"Redirect user to: {authorize_url}") # Step 2: Exchange authorization code for tokens (in callback handler) access_token, expires_in, refresh_token = cs.exchange_token( client_id='your_client_id', client_secret='your_client_secret', redirect_uri='https://yourapp.com/oauth/callback', code='authorization_code_from_callback' ) print(f"Access token: {access_token}") print(f"Expires in: {expires_in} seconds") print(f"Refresh token: {refresh_token}") ``` ``` -------------------------------- ### Retrieve Transactional Email Statistics with Python Source: https://context7.com/campaignmonitor/createsend-python/llms.txt This snippet illustrates how to fetch overall transactional email statistics (sent, bounces, opens, clicks) and message timelines using the createsend-python library. It also shows how to get detailed message information and resend messages. ```python from createsend import Transactional auth = {'api_key': 'your_api_key'} tx = Transactional(auth) # Get overall transactional statistics stats = tx.statistics({ "from": "2024-01-01", "to": "2024-01-31", "timezone": "client" # or specific timezone }) print(f"Sent: {stats.Sent}") print(f"Bounces: {stats.Bounces}") print(f"Opens: {stats.Opens}") print(f"Clicks: {stats.Clicks}") # Get message timeline messages = tx.message_timeline({ "status": "all", # "all", "sent", "bounced", "spam" "sentfromdate": "2024-01-01", "senttodate": "2024-01-31", "count": 50 }) for msg in messages: print(f"Message ID: {msg.MessageID}") print(f" Status: {msg.Status}") print(f" Recipient: {msg.Recipient}") print(f" Sent: {msg.SentAt}") if msg.Status.lower() == 'bounced': print(f" Bounce type: {msg.BounceType}") print(f" Bounce category: {msg.BounceCategory}") # Get detailed message information message = tx.message_details( message_id='message_uuid', statistics=True, exclude_message_body=False ) print(f"Subject: {message.Message.Subject}") print(f"From: {message.Message.From}") print(f"To: {message.Message.To}") print(f"Status: {message.Status}") print(f"Smart Email ID: {message.SmartEmailID}") if hasattr(message, 'Opens'): print(f"Opens: {message.Opens}") if hasattr(message, 'Clicks'): print(f"Clicks: {message.Clicks}") # Resend a transactional message resend_result = tx.message_resend('message_uuid') print(f"Resent as: {resend_result.MessageID}") ``` -------------------------------- ### Initialize Client with Authentication Source: https://github.com/campaignmonitor/createsend-python/blob/master/HISTORY.md Shows how to initialize a client instance by passing an authentication hash as the first argument. ```python auth = {'api_key': 'your api key'} cl = Client(auth, 'your client id') ``` -------------------------------- ### Create and Send Campaigns with createsend-python Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Shows how to create email campaigns using either HTML URLs or templates, send preview emails, schedule or send campaigns immediately, unschedule, and delete campaigns. Requires authentication and client/list/segment IDs. ```python from createsend import Campaign auth = {'api_key': 'your_api_key'} # Create campaign from URLs campaign = Campaign(auth) campaign_id = campaign.create( client_id='your_client_id', subject="June Newsletter", name="June 2024 Newsletter", from_name="Marketing Team", from_email="marketing@example.com", reply_to="reply@example.com", html_url="https://example.com/campaigns/june-newsletter.html", text_url="https://example.com/campaigns/june-newsletter.txt", # Optional list_ids=['list_id_1', 'list_id_2'], segment_ids=['segment_id_1'] ) print(f"Created campaign ID: {campaign_id}") # Create campaign from template campaign_id = campaign.create_from_template( client_id='your_client_id', subject="Product Announcement", name="New Product Launch", from_name="Product Team", from_email="products@example.com", reply_to="products@example.com", list_ids=['list_id_1'], segment_ids=[], template_id='your_template_id', template_content={ "Singlelines": [ {"Content": "Welcome to our newsletter!", "Href": "https://example.com"} ], "Multilines": [ {"Content": "Main content goes here
"} ], "Images": [ {"Content": "https://example.com/image.jpg", "Alt": "Product Image"} ], "Repeaters": [] } ) # Send preview to test recipients campaign = Campaign(auth, campaign_id) campaign.send_preview( recipients=["test@example.com", "preview@example.com"], personalize="fallback" # or "random" ) # Schedule campaign for immediate or future delivery campaign.send( confirmation_email="confirm@example.com", send_date="immediately" # or "2024-06-15 10:00" ) # Unschedule a scheduled campaign campaign.unschedule() # Delete campaign campaign.delete() ``` -------------------------------- ### Manage Clients in Campaign Monitor using Python Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Demonstrates client management operations with the Createsend Python library, including creating new clients, retrieving client details, listing associated lists and campaigns, and configuring PAYG billing. ```python from createsend import Client auth = {'api_key': 'your_api_key'} # Create a new client client = Client(auth) client_id = client.create( company="Acme Corporation", timezone="(GMT+10:00) Canberra, Melbourne, Sydney", country="Australia" ) print(f"Created client ID: {client_id}") # Get existing client details client = Client(auth, 'existing_client_id') details = client.details() print(f"Company: {details.BasicDetails.CompanyName}") print(f"Contact: {details.BasicDetails.ContactName}") # Get all lists for the client lists = client.lists() for lst in lists: print(f"List: {lst.Name} (ID: {lst.ListID})") # Get all campaigns with pagination campaigns = client.campaigns( sent_from_date="2024-01-01", sent_to_date="2024-12-31", page=1, page_size=50, order_direction="desc" ) for campaign in campaigns.Results: print(f"Campaign: {campaign.Subject}") # Get draft and scheduled campaigns drafts = client.drafts() scheduled = client.scheduled() # Set PAYG billing client.set_payg_billing( currency="USD", can_purchase_credits=True, client_pays=True, markup_percentage=10, markup_on_delivery=0.5, markup_per_recipient=0.01 ) ``` -------------------------------- ### Create and Retrieve Client Details Source: https://github.com/campaignmonitor/createsend-python/blob/master/HISTORY.md Demonstrates that created objects now retain their identifiers, allowing for direct retrieval of details after creation. ```python client = Client() client.create("Company Name", "(GMT+10:00) Canberra, Melbourne, Sydney", "Australia") details = client.details() ``` -------------------------------- ### Authenticate with API Key Source: https://github.com/campaignmonitor/createsend-python/blob/master/README.md Initializes the CreateSend client using a standard API key. ```python from createsend import * cs = CreateSend({'api_key': 'your api key'}) clients = cs.clients() ``` -------------------------------- ### Perform Bulk Subscriber Import with Python Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Shows how to import multiple subscribers in a single request. Includes logic for handling import results and identifying failed entries. ```python from createsend import Subscriber auth = {'api_key': 'your_api_key'} subscriber = Subscriber(auth) subscribers_to_import = [ {"EmailAddress": "user1@example.com", "Name": "User One", "CustomFields": [{"Key": "Company", "Value": "Corp A"}], "ConsentToTrack": "Yes"}, {"EmailAddress": "user2@example.com", "Name": "User Two", "CustomFields": [{"Key": "Company", "Value": "Corp B"}], "ConsentToTrack": "Yes"} ] result = subscriber.import_subscribers( list_id='your_list_id', subscribers=subscribers_to_import, resubscribe=True ) if hasattr(result, 'FailureDetails'): for failure in result.FailureDetails: print(f"Failed: {failure.EmailAddress} - {failure.Message}") ``` -------------------------------- ### List Clients and Draft Campaigns Source: https://github.com/campaignmonitor/createsend-python/blob/master/README.md Iterates through all clients and their respective draft campaigns to demonstrate basic API data retrieval. ```python from createsend import * auth = { 'access_token': 'your access token', 'refresh_token': 'your refresh token' } cs = CreateSend(auth) clients = cs.clients() for cl in clients: print("Client: %s" % cl.Name) client = Client(auth, cl.ClientID) print("- Campaigns:") for cm in client.drafts(): print(" - %s" % cm.Subject) ``` -------------------------------- ### Manage Individual Subscribers with Python Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Demonstrates how to add, retrieve, update, and delete individual subscribers. Includes support for custom fields, consent tracking, and SMS contact information. ```python from createsend import Subscriber auth = {'api_key': 'your_api_key'} # Add a single subscriber subscriber = Subscriber(auth) email = subscriber.add( list_id='your_list_id', email_address="john@example.com", name="John Doe", custom_fields=[ {"Key": "Company", "Value": "Acme Inc"}, {"Key": "Interests", "Value": "Technology"}, {"Key": "Interests", "Value": "Marketing"} ], resubscribe=True, consent_to_track="Yes", restart_subscription_based_autoresponders=True ) # Update subscriber subscriber = Subscriber(auth, 'your_list_id', 'john@example.com') subscriber.update( new_email_address="john.doe@example.com", name="John D. Doe", custom_fields=[{"Key": "Company", "Value": "New Corp"}], resubscribe=False, consent_to_track="Unchanged" ) # Unsubscribe and delete subscriber.unsubscribe() subscriber.delete() ``` -------------------------------- ### Authenticate with API Key at Instance Level Source: https://github.com/campaignmonitor/createsend-python/blob/master/HISTORY.md Demonstrates the modern approach to authentication by passing credentials to the CreateSend instance constructor. ```python cs = CreateSend({'api_key': 'your_api_key'}) clients = cs.clients() ``` -------------------------------- ### Manage Email Templates Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Demonstrates how to list, create, retrieve, update, and delete email templates within a client account. Requires authentication and valid client/template IDs. ```python from createsend import Template, Client auth = {'api_key': 'your_api_key'} # List templates for a client client = Client(auth, 'your_client_id') templates = client.templates() for tmpl in templates: print(f"Template: {tmpl.Name} (ID: {tmpl.TemplateID})") # Create a new template template = Template(auth) template_id = template.create( client_id='your_client_id', name="Monthly Newsletter Template", html_url="https://example.com/templates/newsletter.html", zip_url="https://example.com/templates/newsletter-images.zip" ) # Get template details template = Template(auth, 'your_template_id') details = template.details() # Update template template.update( name="Updated Newsletter Template", html_url="https://example.com/templates/newsletter-v2.html", zip_url="https://example.com/templates/newsletter-images-v2.zip" ) # Delete template template.delete() ``` -------------------------------- ### Manage Campaign Monitor Account Details with Python Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Shows how to retrieve account-level information from Campaign Monitor using the Createsend Python library. This includes fetching billing details, system dates, administrators, primary contacts, and available countries/timezones. ```python from createsend import CreateSend auth = {'api_key': 'your_api_key'} cs = CreateSend(auth) # Get billing details billing = cs.billing_details() print(f"Credits: {billing.Credits}") # Get system date in account timezone system_date = cs.systemdate() print(f"System date: {system_date}") # Get all administrators admins = cs.administrators() for admin in admins: print(f"Admin: {admin.Name} ({admin.EmailAddress})") # Get primary contact primary = cs.get_primary_contact() print(f"Primary contact: {primary.EmailAddress}") # Set new primary contact cs.set_primary_contact("newemail@example.com") # Get available countries and timezones countries = cs.countries() timezones = cs.timezones() print(f"Available countries: {len(countries)}") print(f"Available timezones: {len(timezones)}") ``` -------------------------------- ### Authenticate with Createsend Python Library Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Demonstrates how to authenticate with the Createsend Python library using either OAuth tokens (with automatic refresh) or simple API keys. This is the first step to interacting with the Campaign Monitor API. ```python from createsend import CreateSend, Client, ExpiredOAuthToken # OAuth authentication with automatic token refresh auth = { 'access_token': 'your_access_token', 'refresh_token': 'your_refresh_token' } cs = CreateSend(auth) try: clients = cs.clients() for client in clients: print(f"Client: {client.Name} (ID: {client.ClientID})") except ExpiredOAuthToken: # Refresh the token and retry new_access_token, expires_in, new_refresh_token = cs.refresh_token() print(f"Token refreshed, expires in {expires_in} seconds") clients = cs.clients() # API key authentication (simpler approach) auth_simple = {'api_key': 'your_api_key'} cs_simple = CreateSend(auth_simple) clients = cs_simple.clients() ``` -------------------------------- ### Create and Manage Subscriber Segments with Python Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Covers creating segments using rule groups and retrieving segment details or active subscribers within a segment. ```python from createsend import Segment auth = {'api_key': 'your_api_key'} segment = Segment(auth) segment_id = segment.create( list_id='your_list_id', title="Active Tech Subscribers", rulegroups=[ {"Rules": [{"RuleType": "EmailAddress", "Clause": "CONTAINS @techcompany.com"}]}, {"Rules": [{"RuleType": "DateSubscribed", "Clause": "AFTER 2024-01-01"}]} ] ) # Get active subscribers in segment subscribers = segment.subscribers(page=1, page_size=100) print(f"Subscribers in segment: {subscribers.TotalNumberOfRecords}") ``` -------------------------------- ### Manage Webhooks Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Set up and manage webhooks to receive real-time notifications for subscriber events such as subscriptions or updates. ```python from createsend import List lst = List({'api_key': 'your_api_key'}, 'your_list_id') webhook_id = lst.create_webhook(events=["Subscribe", "Deactivate"], url="https://yourapp.com/webhook", payload_format="json") lst.test_webhook(webhook_id) lst.deactivate_webhook(webhook_id) lst.delete_webhook(webhook_id) ``` -------------------------------- ### Manage Smart Emails with Python Source: https://context7.com/campaignmonitor/createsend-python/llms.txt This snippet demonstrates how to list, retrieve details for, and send smart emails using the createsend-python library. It covers basic operations and sending with custom data. ```python from createsend import Transactional auth = {'api_key': 'your_api_key'} tx = Transactional(auth) # List all smart emails smart_emails = tx.smart_email_list(status="active", client_id='optional_client_id') for email in smart_emails: print(f"Smart Email: {email.Name} (ID: {email.ID})") # Get smart email details details = tx.smart_email_details('smart_email_id') print(f"Subject: {details.Subject}") print(f"From: {details.From}") print(f"Status: {details.Status}") # Send a smart email result = tx.smart_email_send( smart_email_id='your_smart_email_id', to=["recipient@example.com"], consent_to_track="Yes", cc=["cc@example.com"], bcc=["bcc@example.com"], data={ "firstname": "John", "lastname": "Doe", "orderid": "12345", "items": [ {"name": "Product A", "price": "$29.99"}, {"name": "Product B", "price": "$49.99"} ] }, add_recipients_to_list="optional_list_id" ) for sent in result: print(f"Sent to: {sent.Recipient} - Message ID: {sent.MessageID}") ``` -------------------------------- ### Authenticate with OAuth Tokens Source: https://github.com/campaignmonitor/createsend-python/blob/master/README.md Initializes the CreateSend client using stored OAuth access and refresh tokens to make API calls. ```python from createsend import * cs = CreateSend({ 'access_token': 'your access token', 'refresh_token': 'your refresh token' }) clients = cs.clients() ``` -------------------------------- ### Handle Campaign Creation Errors (Python) Source: https://github.com/campaignmonitor/createsend-python/blob/master/README.md Illustrates how to catch and handle specific API errors, such as BadRequest, when creating a campaign with invalid parameters. It shows how to access error codes and messages returned by the API. ```Python from createsend import * campaign = Campaign({ 'access_token': 'your access token', 'refresh_token': 'your refresh token' }) try: id = campaign.create("4a397ccaaa55eb4e6aa1221e1e2d7122", "", "", "", "", "", "", "", [], []) print("New campaign ID: %s" % id) except BadRequest as br: print("Bad request error: %s" % br) print("Error Code: %s" % br.data.Code) print("Error Message: %s" % br.data.Message) except Exception as e: print("Error: %s" % e) ``` -------------------------------- ### Create Segment with Rule Groups Source: https://github.com/campaignmonitor/createsend-python/blob/master/HISTORY.md Demonstrates the updated segment creation pattern using RuleGroups instead of the deprecated Rules structure. ```python segment.create(list.ListID, 'Python API Segment', [ { "Rules": [ { "RuleType": "EmailAddress", "Clause": "CONTAINS pyapi.com" } ] } ]) ``` -------------------------------- ### Generate Campaign Monitor SSO URL in Python Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Shows how to generate a Single Sign-On (SSO) URL for Campaign Monitor using the createsend-python library. This allows users to log in to Campaign Monitor from your application seamlessly. It requires authentication details and target user information. ```python from createsend import CreateSend auth = {'api_key': 'your_api_key'} cs = CreateSend(auth) # Generate SSO session URL session = cs.external_session_url( email="user@example.com", chrome="tabs", # "all", "tabs", or "none" url="/subscribers/", # Target URL after login integrator_id="your_integrator_id", # Contact CM support to get this client_id="target_client_id" ) # Redirect user to the session URL print(f"SSO URL: {session.SessionUrl}") ``` -------------------------------- ### Manage Journeys with Python Source: https://context7.com/campaignmonitor/createsend-python/llms.txt This code demonstrates how to interact with marketing automation journeys using the createsend-python library. It covers fetching all journeys for a client, retrieving journey summaries, and accessing statistics for specific journey emails. ```python from createsend import Client, Journey, JourneyEmail auth = {'api_key': 'your_api_key'} # Get all journeys for a client client = Client(auth, 'your_client_id') journeys = client.journeys() for j in journeys: print(f"Journey: {j.Name} (ID: {j.JourneyID})") print(f" Status: {j.Status}") print(f" Trigger type: {j.TriggerType}") # Get journey summary journey = Journey(auth, 'your_journey_id') summary = journey.summary() print(f"Journey: {summary.Name}") print(f"Status: {summary.Status}") print(f"Trigger: {summary.TriggerType}") for email in summary.Emails: print(f" Email: {email.Name} (ID: {email.EmailID})") # Get journey email statistics journey_email = JourneyEmail(auth, 'journey_email_id') # Get recipients recipients = journey_email.recipients( date="2024-01-01", page=1, page_size=100, order_direction="desc" ) for recipient in recipients.Results: print(f"Recipient: {recipient.EmailAddress}") # Get opens opens = journey_email.opens(date="2024-01-01", page=1) for open_event in opens.Results: print(f"Opened: {open_event.EmailAddress} at {open_event.Date}") # Get clicks clicks = journey_email.clicks(date="2024-01-01", page=1) for click in clicks.Results: print(f"Clicked: {click.EmailAddress} - {click.URL}") # Get bounces bounces = journey_email.bounces(page=1) for bounce in bounces.Results: print(f"Bounced: {bounce.EmailAddress} - {bounce.BounceType}") ``` -------------------------------- ### Authentication Methods Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Demonstrates how to authenticate with the Campaign Monitor API using either OAuth tokens (with refresh capability) or a simple API key. ```APIDOC ## Authentication The library supports two authentication methods: OAuth tokens with refresh capability and simple API keys for basic integration scenarios. ```python from createsend import CreateSend, Client, ExpiredOAuthToken # OAuth authentication with automatic token refresh auth = { 'access_token': 'your_access_token', 'refresh_token': 'your_refresh_token' } cs = CreateSend(auth) try: clients = cs.clients() for client in clients: print(f"Client: {client.Name} (ID: {client.ClientID})") except ExpiredOAuthToken: # Refresh the token and retry new_access_token, expires_in, new_refresh_token = cs.refresh_token() print(f"Token refreshed, expires in {expires_in} seconds") clients = cs.clients() # API key authentication (simpler approach) auth_simple = {'api_key': 'your_api_key'} cs_simple = CreateSend(auth_simple) clients = cs_simple.clients() ``` ``` -------------------------------- ### Retrieve Subscriber Details Source: https://github.com/campaignmonitor/createsend-python/blob/master/HISTORY.md Shows the simplified syntax for retrieving subscriber details without redundant arguments. ```python subscriber = Subscriber(auth, 'listid', 'me@test.com').get() ``` -------------------------------- ### Manage Client-Level Users Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Handles the lifecycle of client-level users including listing, adding, updating, and removing access. Access levels define the permissions of the user. ```python from createsend import Person, Client auth = {'api_key': 'your_api_key'} # List all people for a client client = Client(auth, 'your_client_id') people = client.people() # Add a new person person = Person(auth) result = person.add( client_id='your_client_id', email_address="user@example.com", name="New User", access_level=1023 ) # Get person details person = Person(auth, 'your_client_id', 'user@example.com') details = person.get() # Update person person.update( new_email_address="newuser@example.com", name="Updated User Name", access_level=512 ) # Delete person person.delete() ``` -------------------------------- ### Retrieve Campaign Analytics with createsend-python Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Provides Python code to fetch various campaign performance metrics, including summary statistics, target lists/segments, recipients, opens, clicks, bounces, unsubscribes, spam complaints, and email client usage. Requires campaign ID and authentication. ```python from createsend import Campaign auth = {'api_key': 'your_api_key'} campaign = Campaign(auth, 'your_campaign_id') # Get campaign summary summary = campaign.summary() print(f"Campaign: {summary.Name}") print(f"Recipients: {summary.Recipients}") print(f"Total opened: {summary.TotalOpened}") print(f"Unique opened: {summary.UniqueOpened}") print(f"Clicks: {summary.Clicks}") print(f"Unsubscribed: {summary.Unsubscribed}") print(f"Bounced: {summary.Bounced}") print(f"Spam complaints: {summary.SpamComplaints}") # Get lists and segments the campaign was sent to targets = campaign.lists_and_segments() print("Lists:", [lst.Name for lst in targets.Lists]) print("Segments:", [seg.Title for seg in targets.Segments]) # Get recipients with pagination recipients = campaign.recipients(page=1, page_size=100) for recipient in recipients.Results: print(f"Recipient: {recipient.EmailAddress}") # Get opens with filtering opens = campaign.opens( date="2024-01-01", page=1, page_size=100, order_field="date", order_direction="desc" ) for open_event in opens.Results: print(f"Opened by: {open_event.EmailAddress} at {open_event.Date}") print(f" Location: {open_event.City}, {open_event.Region}, {open_event.CountryName}") # Get clicks with details clicks = campaign.clicks(date="2024-01-01", page=1, page_size=100) for click in clicks.Results: print(f"Click by: {click.EmailAddress}") print(f" URL: {click.URL}") print(f" Location: {click.Latitude}, {click.Longitude}") # Get bounces bounces = campaign.bounces(page=1, page_size=100) for bounce in bounces.Results: print(f"Bounced: {bounce.EmailAddress} - {bounce.BounceType}") # Get unsubscribes unsubscribes = campaign.unsubscribes(page=1, page_size=100) for unsub in unsubscribes.Results: print(f"Unsubscribed: {unsub.EmailAddress} at {unsub.Date}") # Get spam complaints spam = campaign.spam(page=1, page_size=100) for complaint in spam.Results: print(f"Spam complaint: {complaint.EmailAddress}") # Get email client usage statistics email_clients = campaign.email_client_usage() for client in email_clients: print(f"{client.Client}: {client.Percentage}%") ``` -------------------------------- ### Handle Campaign Monitor API Errors in Python Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Demonstrates how to handle various API errors from Campaign Monitor using the createsend-python library. It covers specific exceptions like BadRequest, Unauthorized, ExpiredOAuthToken, NotFound, ClientError, and ServerError, along with a general Exception catch-all. It also shows how to validate consent to track values. ```python from createsend import \ CreateSend, Campaign, Subscriber, \ CreateSendError, BadRequest, Unauthorized, \ ExpiredOAuthToken, NotFound, ClientError, ServerError auth = { 'access_token': 'your_access_token', 'refresh_token': 'your_refresh_token' } cs = CreateSend(auth) try: # Attempt an API call campaign = Campaign(auth) campaign_id = campaign.create( client_id='your_client_id', subject="", # Empty subject will cause an error name="Test", from_name="", from_email="invalid-email", reply_to="", html_url="", text_url="", list_ids=[], segment_ids=[] ) except BadRequest as e: # Handle validation errors (400) print(f"Bad request: {e}") print(f"Error code: {e.data.Code}") print(f"Error message: {e.data.Message}") except ExpiredOAuthToken as e: # Handle expired OAuth token (401 with code 121) print("OAuth token expired, refreshing...") new_token, expires_in, new_refresh = cs.refresh_token() print(f"New token obtained, expires in {expires_in} seconds") # Retry the operation with new credentials except Unauthorized as e: # Handle other authentication errors (401) print(f"Unauthorized: {e}") print(f"Code: {e.data.Code}") except NotFound: # Handle 404 errors print("Resource not found") except ClientError as e: # Handle other 4xx errors print(f"Client error: {e}") except ServerError as e: # Handle 5xx errors print(f"Server error: {e}") except Exception as e: # Handle unexpected errors print(f"Unexpected error: {e}") # Validate consent to track values from createsend.utils import validate_consent_to_track try: validate_consent_to_track("invalid") except ClientError as e: print(f"Invalid consent value: {e}") # Valid values are: "yes", "no", "unchanged" ``` -------------------------------- ### POST /campaigns Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Creates a new email campaign using either an external URL or a pre-defined template. ```APIDOC ## POST /campaigns ### Description Creates a new email campaign. Can be created from URLs or from a template with specific content mappings. ### Method POST ### Endpoint /campaigns ### Parameters #### Request Body - **client_id** (string) - Required - The ID of the client - **subject** (string) - Required - Campaign subject line - **name** (string) - Required - Internal campaign name - **html_url** (string) - Optional - URL for HTML content - **template_id** (string) - Optional - ID of the template to use - **template_content** (object) - Optional - Content mapping for templates ### Request Example { "client_id": "your_client_id", "subject": "June Newsletter", "name": "June 2024 Newsletter" } ### Response #### Success Response (201) - **campaign_id** (string) - The unique identifier for the created campaign ``` -------------------------------- ### Single Sign-On (SSO) API Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Initiate external login sessions for seamless Campaign Monitor access from your application by generating an SSO URL. ```APIDOC ## Single Sign-On Initiate external login sessions for seamless Campaign Monitor access from your application. ```python from createsend import CreateSend auth = {'api_key': 'your_api_key'} cs = CreateSend(auth) # Generate SSO session URL session = cs.external_session_url( email="user@example.com", chrome="tabs", # "all", "tabs", or "none" url="/subscribers/", # Target URL after login integrator_id="your_integrator_id", # Contact CM support to get this client_id="target_client_id" ) # Redirect user to the session URL print(f"SSO URL: {session.SessionUrl}") ``` ``` -------------------------------- ### Send Transactional Emails with createsend-python Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Illustrates how to send individual transactional emails using the Transactional class from the createsend-python library. This method supports sending emails via smart email templates or custom HTML. Requires API key authentication. ```python from createsend import Transactional import base64 auth = {'api_key': 'your_api_key'} tx = Transactional(auth) # Example usage for sending a transactional email would follow here, # typically involving methods like tx.send_email(...) # This snippet only shows initialization. ``` -------------------------------- ### POST /subscribers/import Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Import multiple subscribers in a single bulk operation with support for error reporting on failed records. ```APIDOC ## POST /subscribers/import ### Description Imports a batch of subscribers into a list, providing summary statistics and details on any failures. ### Method POST ### Endpoint /subscribers/{list_id}/import ### Parameters #### Path Parameters - **list_id** (string) - Required - The unique identifier of the subscriber list. #### Request Body - **subscribers** (array) - Required - A list of subscriber objects containing email, name, and custom fields. - **resubscribe** (boolean) - Optional - Whether to resubscribe existing users. ### Request Example { "subscribers": [{"EmailAddress": "user1@example.com", "Name": "User One"}] } ### Response #### Success Response (200) - **TotalNewSubscribers** (integer) - Count of newly added subscribers. - **TotalExistingSubscribers** (integer) - Count of updated subscribers. - **FailureDetails** (array) - List of errors for failed imports. #### Response Example { "TotalNewSubscribers": 1, "TotalExistingSubscribers": 0 } ``` -------------------------------- ### Client Management API Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Enables the creation, configuration, and management of Campaign Monitor clients, including billing settings, credit transfers, and accessing client-specific resources. ```APIDOC ## Client Management Create, configure, and manage Campaign Monitor clients including billing settings, credit transfers, and accessing client-specific resources. ```python from createsend import Client auth = {'api_key': 'your_api_key'} # Create a new client client = Client(auth) client_id = client.create( company="Acme Corporation", timezone="(GMT+10:00) Canberra, Melbourne, Sydney", country="Australia" ) print(f"Created client ID: {client_id}") # Get existing client details client = Client(auth, 'existing_client_id') details = client.details() print(f"Company: {details.BasicDetails.CompanyName}") print(f"Contact: {details.BasicDetails.ContactName}") # Get all lists for the client lists = client.lists() for lst in lists: print(f"List: {lst.Name} (ID: {lst.ListID})") # Get all campaigns with pagination campaigns = client.campaigns( sent_from_date="2024-01-01", sent_to_date="2024-12-31", page=1, page_size=50, order_direction="desc" ) for campaign in campaigns.Results: print(f"Campaign: {campaign.Subject}") # Get draft and scheduled campaigns drafts = client.drafts() scheduled = client.scheduled() # Set PAYG billing client.set_payg_billing( currency="USD", can_purchase_credits=True, client_pays=True, markup_percentage=10, markup_on_delivery=0.5, markup_per_recipient=0.01 ) ``` ``` -------------------------------- ### Handle Expired OAuth Tokens Source: https://github.com/campaignmonitor/createsend-python/blob/master/README.md Demonstrates how to catch the ExpiredOAuthToken exception and refresh the access token automatically. ```python from createsend import * try: cs = CreateSend({ 'access_token': 'your access token', 'refresh_token': 'your refresh token' }) clients = cs.clients() except ExpiredOAuthToken as eot: access_token, expires_in, refresh_token = cs.refresh_token() clients = cs.clients() except Exception as e: print("Error: %s" % e) ``` -------------------------------- ### Implement OAuth Authorization Flow in Python Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Provides Python code to implement the OAuth 2.0 authorization flow for Campaign Monitor. This includes generating an authorization URL for user redirection and exchanging an authorization code for access and refresh tokens. ```python from createsend import CreateSend cs = CreateSend() # Step 1: Generate authorization URL for user redirect authorize_url = cs.authorize_url( client_id='your_client_id', redirect_uri='https://yourapp.com/oauth/callback', scope='ManageLists,ImportSubscribers,SendCampaigns', state='optional_state_data' ) print(f"Redirect user to: {authorize_url}") # Step 2: Exchange authorization code for tokens (in callback handler) access_token, expires_in, refresh_token = cs.exchange_token( client_id='your_client_id', client_secret='your_client_secret', redirect_uri='https://yourapp.com/oauth/callback', code='authorization_code_from_callback' ) print(f"Access token: {access_token}") print(f"Expires in: {expires_in} seconds") print(f"Refresh token: {refresh_token}") ``` -------------------------------- ### Manage Segment Rules and Operations Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Demonstrates how to add rule groups, update segments with new rules, clear all rules, and delete a segment using the createsend-python library. This is useful for dynamic list management. ```python from createsend import Segment # Assuming 'segment' is an initialized Segment object # segment = Segment(auth, 'segment_id') # Add another rule group segment.add_rulegroup({ "Rules": [ {"RuleType": "Name", "Clause": "CONTAINS John"} ] }) # Update segment segment.update( title="Updated Tech Subscribers", rulegroups=[ { "Rules": [ {"RuleType": "EmailAddress", "Clause": "CONTAINS @newdomain.com"} ] } ] ) # Clear all rules and delete segment segment.clear_rules() segment.delete() ``` -------------------------------- ### Manage Client Credits and Suppression Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Perform administrative tasks on client accounts, including transferring credits, managing suppression lists, and deleting client records. ```python result = client.transfer_credits(credits=1000, can_use_my_credits_when_they_run_out=True) print(f"Account credits: {result.AccountCredits}") print(f"Client credits: {result.ClientCredits}") suppressed = client.suppressionlist(page=1, page_size=100) for subscriber in suppressed.Results: print(f"Suppressed: {subscriber.EmailAddress}") client.suppress("spam@example.com") client.suppress(["bad1@example.com", "bad2@example.com"]) client.unsuppress("recovered@example.com") client.delete() ``` -------------------------------- ### Manage Subscriber Lists Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Create, retrieve, update, and delete subscriber lists. Includes functionality for fetching list statistics and filtering subscribers by status. ```python from createsend import List auth = {'api_key': 'your_api_key'} lst = List(auth) list_id = lst.create(client_id='your_client_id', title="Newsletter Subscribers", unsubscribe_page="https://example.com/unsubscribe", confirmed_opt_in=False, confirmation_success_page="https://example.com/confirmed", unsubscribe_setting="AllClientLists") lst = List(auth, 'your_list_id') details = lst.details() stats = lst.stats() active = lst.active(date="2024-01-01", page=1, page_size=100) lst.update(title="Updated Newsletter", confirmed_opt_in=True) lst.delete() ``` -------------------------------- ### Error Handling API Source: https://context7.com/campaignmonitor/createsend-python/llms.txt Demonstrates how to handle various API errors, including bad requests, authentication failures, expired OAuth tokens, and server-side issues. ```APIDOC ## Error Handling Handle API errors including bad requests, authentication failures, and expired OAuth tokens. ```python from createsend import ( CreateSend, Campaign, Subscriber, CreateSendError, BadRequest, Unauthorized, ExpiredOAuthToken, NotFound, ClientError, ServerError ) auth = { 'access_token': 'your_access_token', 'refresh_token': 'your_refresh_token' } cs = CreateSend(auth) try: # Attempt an API call campaign = Campaign(auth) campaign_id = campaign.create( client_id='your_client_id', subject="", # Empty subject will cause an error name="Test", from_name="", from_email="invalid-email", reply_to="", html_url="", text_url="", list_ids=[], segment_ids=[] ) except BadRequest as e: # Handle validation errors (400) print(f"Bad request: {e}") print(f"Error code: {e.data.Code}") print(f"Error message: {e.data.Message}") except ExpiredOAuthToken as e: # Handle expired OAuth token (401 with code 121) print("OAuth token expired, refreshing...") new_token, expires_in, new_refresh = cs.refresh_token() print(f"New token obtained, expires in {expires_in} seconds") # Retry the operation with new credentials except Unauthorized as e: # Handle other authentication errors (401) print(f"Unauthorized: {e}") print(f"Code: {e.data.Code}") except NotFound: # Handle 404 errors print("Resource not found") except ClientError as e: # Handle other 4xx errors print(f"Client error: {e}") except ServerError as e: # Handle 5xx errors print(f"Server error: {e}") except Exception as e: # Handle unexpected errors print(f"Unexpected error: {e}") # Validate consent to track values from createsend.utils import validate_consent_to_track try: validate_consent_to_track("invalid") except ClientError as e: print(f"Invalid consent value: {e}") # Valid values are: "yes", "no", "unchanged" ``` ```