Python Examples

Python integration examples using the Metigan SDK. Learn how to send emails, manage contacts, and integrate Metigan into your Python applications.

Installation

install.shTerminal
1
2
3
pip install metigan
# or
pip3 install metigan

Basic Setup

basic.pyPython
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from metigan import MetiganClient

# Initialize the client
client = MetiganClient(api_key="your-api-key")

# Send email
result = client.email.send_email(
    from_address="Sender <sender@example.com>",
    recipients=["customer@email.com"],
    subject="Welcome!",
    content="<h1>Hello!</h1><p>Thank you for signing up.</p>"
)

if result["success"]:
    print("Email sent successfully!")
    print(f"Emails remaining: {result.get('emailsRemaining', 'N/A')}")

Sending Emails

Basic Email

send-email.pyPython
1
2
3
4
5
6
result = client.email.send_email(
    from_address="sender@example.com",
    recipients=["recipient@example.com"],
    subject="Email Subject",
    content="<h1>HTML Content</h1><p>This is the email body.</p>"
)

Email with CC and BCC

send-email-cc.pyPython
1
2
3
4
5
6
7
8
9
result = client.email.send_email(
    from_address="company@email.com",
    recipients=["main@email.com"],
    subject="Meeting",
    content="Email content",
    cc=["copy@email.com"],
    bcc=["hidden-copy@email.com"],
    reply_to="reply-here@email.com"
)

Email with Attachments

send-email-attachment.pyPython
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
with open("document.pdf", "rb") as f:
    file_data = f.read()

result = client.email.send_email(
    from_address="company@email.com",
    recipients=["customer@email.com"],
    subject="Important Document",
    content="Please find the document attached.",
    attachments=[
        {
            "content": file_data,
            "filename": "document.pdf",
            "content_type": "application/pdf"
        }
    ]
)

Email with Template

send-email-template.pyPython
1
2
3
4
5
6
7
8
9
result = client.email.send_email_with_template(
    template_id="template-123",
    variables={
        "name": "John Doe",
        "company": "Acme Inc"
    },
    from_address="sender@example.com",
    recipients=["recipient@example.com"]
)

Contact Management

Create Contact

create-contact.pyPython
1
2
3
4
5
6
7
contact = client.contacts.create(
    email="new@email.com",
    first_name="Jane",
    last_name="Doe",
    audience_id="audience-123",
    tags=["customer", "newsletter"]
)

Get Contact

get-contact.pyPython
1
2
3
4
5
# By ID
contact = client.contacts.get("contact-456")

# By email
contact = client.contacts.get_by_email("jane@email.com", "audience-123")

List Contacts

list-contacts.pyPython
1
2
3
4
5
6
7
8
9
10
result = client.contacts.list(
    audience_id="audience-123",
    status="subscribed",
    page=1,
    limit=50
)

print(f"Total contacts: {result['pagination']['total']}")
for contact in result["contacts"]:
    print(f"{contact['email']}: {contact.get('first_name', 'N/A')}")

Update Contact

update-contact.pyPython
1
2
3
4
5
updated = client.contacts.update(
    contact_id="contact-456",
    first_name="Jane Marie",
    tags=["customer", "vip"]
)

Manage Subscription

manage-subscription.pyPython
1
2
3
4
5
# Subscribe
client.contacts.subscribe("contact-456")

# Unsubscribe
client.contacts.unsubscribe("contact-456")

Manage Tags

manage-tags.pyPython
1
2
3
4
5
# Add tags
client.contacts.add_tags("contact-456", ["vip", "black-friday"])

# Remove tags
client.contacts.remove_tags("contact-456", ["test"])

Audience Management

Create Audience

create-audience.pyPython
1
2
3
4
audience = client.audiences.create(
    name="Main Newsletter",
    description="Main subscriber list"
)

List Audiences

list-audiences.pyPython
1
2
3
4
result = client.audiences.list(page=1, limit=10)

for audience in result["audiences"]:
    print(f"{audience['name']}: {audience['count']} contacts")

Get Audience Statistics

audience-stats.pyPython
1
2
3
4
5
stats = client.audiences.get_stats("audience-123")

print(f"Total: {stats['total']}")
print(f"Subscribed: {stats['subscribed']}")
print(f"Unsubscribed: {stats['unsubscribed']}")

Forms

Submit Form

submit-form.pyPython
1
2
3
4
5
6
7
8
9
10
result = client.forms.submit(
    form_id="form-123",
    data={
        "field-email": "user@email.com",
        "field-name": "John Doe",
        "field-message": "Hello, I would like more information."
    }
)

print(result["message"])

Get Form

get-form.pyPython
1
2
3
form = client.forms.get("form-123")
print(form["title"])
print(form["fields"])

Error Handling

error-handling.pyPython
1
2
3
4
5
6
7
8
9
10
11
12
from metigan import MetiganClient, ApiError, ValidationError

try:
    result = client.email.send_email(options)
except ValidationError as e:
    print(f"Validation Error: {e.message}")
    if e.field:
        print(f"Field: {e.field}")
except ApiError as e:
    print(f"API Error: {e.status_code} - {e.message}")
except Exception as e:
    print(f"Unknown error: {e}")

Advanced Configuration

advanced-config.pyPython
1
2
3
4
5
6
7
8
9
from metigan import MetiganClient

client = MetiganClient(
    api_key="your-api-key",
    timeout=30,        # Optional, defaults to 30 seconds
    retry_count=3,     # Optional, defaults to 3
    retry_delay=2,     # Optional, defaults to 2 seconds
    debug=False        # Optional, defaults to False
)

Flask Example

flask-example.pyPython
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from flask import Flask, request, jsonify
from metigan import MetiganClient
import os

app = Flask(__name__)
client = MetiganClient(api_key=os.getenv("METIGAN_API_KEY"))

@app.route("/send-email", methods=["POST"])
def send_email():
    data = request.get_json()
    
    try:
        result = client.email.send_email(
            from_address="noreply@example.com",
            recipients=[data["to"]],
            subject=data["subject"],
            content=data["content"]
        )
        
        return jsonify({
            "success": result.get("success"),
            "message": result.get("message")
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
    app.run(debug=True)

Django Example

views.pyPython
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from metigan import MetiganClient
import os
import json

client = MetiganClient(api_key=os.getenv("METIGAN_API_KEY"))

@csrf_exempt
@require_http_methods(["POST"])
def send_email(request):
    try:
        data = json.loads(request.body)
        
        result = client.email.send_email(
            from_address="noreply@example.com",
            recipients=[data["to"]],
            subject=data["subject"],
            content=data["content"]
        )
        
        return JsonResponse({
            "success": result.get("success"),
            "message": result.get("message")
        })
    except Exception as e:
        return JsonResponse({"error": str(e)}, status=500)
Environment Variables

Use environment variables to store your API key securely. Set METIGAN_API_KEY before running your application.