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"]
)

OTP Email (Verification Code)

Send One-Time Password emails with priority delivery and built-in rate limiting.

otp-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
29
30
31
32
33
34
35
36
import random
from metigan import MetiganClient

client = MetiganClient(api_key="your-api-key")

def send_verification_code(user_email: str) -> dict:
    """Send OTP with default template"""
    code = str(random.randint(100000, 999999))
    
    result = client.email.send_otp(
        to=user_email,
        from_address="security@myapp.com",
        code=code,
        app_name="MyApp",
        expires_in_minutes=10
    )
    
    if result.get("success"):
        print(f"OTP sent! Tracking: {result['trackingId']}")
        return {"success": True, "code": code}
    return {"success": False, "error": result.get("error")}

def send_branded_otp(user_email: str, template_id: str) -> dict:
    """Send OTP with custom branded template"""
    code = str(random.randint(100000, 999999))
    
    result = client.email.send_otp(
        to=user_email,
        from_address="security@myapp.com",
        code=code,
        app_name="MyApp",
        expires_in_minutes=5,
        template_id=template_id  # Custom template
    )
    
    return result

Transactional Email (Fast Lane)

Send time-sensitive transactional emails like password resets, receipts, and confirmations.

transactional-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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from metigan import MetiganClient

client = MetiganClient(api_key="your-api-key")

def send_password_reset(user_email: str, reset_link: str) -> dict:
    """Send password reset email"""
    result = client.email.send_transactional(
        to=user_email,
        from_address="security@myapp.com",
        subject="Reset Your Password",
        content=f"""
            <h1>Password Reset</h1>
            <p>Click the link below to reset your password:</p>
            <a href="{reset_link}" style="padding: 12px 24px; background: #2563eb; 
               color: white; text-decoration: none; border-radius: 8px;">
                Reset Password
            </a>
            <p style="color: #666; margin-top: 20px;">This link expires in 1 hour.</p>
        """
    )
    return result

def send_order_confirmation(order: dict) -> dict:
    """Send order confirmation email"""
    result = client.email.send_transactional(
        to=order["customer_email"],
        from_address="orders@myshop.com",
        subject=f"Order Confirmed #{order['id']}",
        content=f"""
            <h1>Thank you for your order!</h1>
            <p>Order #{order['id']} has been confirmed.</p>
            <p><strong>Total:</strong> $""" + f"""{order['total']:.2f}</p>
            <a href="https://myshop.com/orders/{order['id']}">Track Your Order</a>
        """
    )
    return result

def send_payment_receipt(payment: dict) -> dict:
    """Send payment receipt email"""
    result = client.email.send_transactional(
        to=payment["customer_email"],
        from_address="billing@myservice.com",
        subject=f"Payment Receipt - {payment['currency']} {payment['amount']:.2f}",
        content=f"""
            <h1>Payment Receipt</h1>
            <p>Thank you for your payment.</p>
            <div style="background: #f5f5f5; padding: 20px; border-radius: 8px;">
                <p><strong>Amount:</strong> {payment['currency']} {payment['amount']:.2f}</p>
                <p><strong>Receipt ID:</strong> {payment['id']}</p>
                <p><strong>Date:</strong> {payment['date']}</p>
            </div>
        """
    )
    return result

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.