Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /genropy_genro-mail-proxy /examples /client /example_client.py
| #!/usr/bin/env python3 | |
| """ | |
| Example Client for genro-mail-proxy | |
| This standalone server demonstrates how to integrate with genro-mail-proxy. | |
| It provides endpoints to generate test messages and shows the recommended pattern: | |
| 1. Write message to local database | |
| 2. Submit message to mail service via REST API | |
| 3. Trigger immediate dispatch (optional, best-effort) | |
| 4. Handle delivery reports via proxy_sync endpoint | |
| Usage: | |
| python3 example_client.py | |
| Then send test messages: | |
| curl -X POST http://localhost:8081/send-test-email | |
| curl -X POST http://localhost:8081/send-test-email?count=5 | |
| """ | |
| import configparser | |
| import logging | |
| import random | |
| import sqlite3 | |
| import time | |
| from datetime import datetime | |
| from typing import Optional | |
| import aiohttp | |
| import uvicorn | |
| from fastapi import FastAPI, HTTPException, Query, Request | |
| # Configure logging | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format='[%(asctime)s] [%(levelname)s] %(message)s', | |
| datefmt='%Y-%m-%d %H:%M:%S' | |
| ) | |
| logger = logging.getLogger(__name__) | |
| class ExampleClient: | |
| """ | |
| Example client demonstrating integration with genro-mail-proxy. | |
| This simulates a real application (like Genropy) that needs to send emails. | |
| It shows the recommended decoupling pattern: | |
| - Local persistence first (your database) | |
| - Async submission to mail service | |
| - Optional immediate trigger | |
| - Delivery report handling | |
| """ | |
| def __init__(self, config_path: str = "example_config.ini"): | |
| self.config = configparser.ConfigParser() | |
| self.config.read(config_path) | |
| # Server configuration | |
| self.port = self.config.getint('server', 'port', fallback=9090) | |
| # Mail service connection | |
| self.mail_service_url = self.config.get('mail_service', 'url', fallback='http://localhost:8000') | |
| self.api_token = self.config.get('mail_service', 'api_token', fallback='your-secret-token') | |
| # Test message configuration | |
| self.test_recipient = self.config.get('test', 'recipient_email') | |
| self.test_sender = self.config.get('test', 'sender_email', fallback='test@example.com') | |
| self.test_sender_name = self.config.get('test', 'sender_name', fallback='Example Client') | |
| self.account_id = self.config.get('test', 'account_id', fallback=None) | |
| # Local database (simulating your application's DB) | |
| self.db_path = self.config.get('database', 'path', fallback='example_client.db') | |
| self._init_database() | |
| logger.info(f"Example client initialized") | |
| logger.info(f"Server port: {self.port}") | |
| logger.info(f"Mail service: {self.mail_service_url}") | |
| logger.info(f"Test recipient: {self.test_recipient}") | |
| logger.info(f"Account ID: {self.account_id}") | |
| logger.info(f"Local database: {self.db_path}") | |
| def _init_database(self): | |
| """Initialize local database to track messages.""" | |
| conn = sqlite3.connect(self.db_path) | |
| conn.execute(""" | |
| CREATE TABLE IF NOT EXISTS outbound_emails ( | |
| id TEXT PRIMARY KEY, | |
| recipient TEXT NOT NULL, | |
| subject TEXT NOT NULL, | |
| body TEXT NOT NULL, | |
| created_at INTEGER NOT NULL, | |
| submitted_at INTEGER, | |
| delivered_at INTEGER, | |
| error TEXT, | |
| status TEXT DEFAULT 'pending' | |
| ) | |
| """) | |
| conn.execute(""" | |
| CREATE INDEX IF NOT EXISTS idx_status ON outbound_emails(status) | |
| """) | |
| conn.commit() | |
| conn.close() | |
| logger.info("Local database initialized") | |
| async def create_test_message(self, custom_subject: Optional[str] = None) -> dict: | |
| """ | |
| Step 1: Create message in local database (YOUR application's DB). | |
| This represents your application committing a message before submission. | |
| Even if the mail service is down, this message is persisted locally. | |
| """ | |
| message_id = f"test_{int(time.time() * 1000)}_{random.randint(1000, 9999)}" | |
| # Generate realistic test content | |
| subjects = [ | |
| "Test Email from Example Client", | |
| "Integration Test Message", | |
| "Sample Email via Async Mail Service", | |
| "Test: Email Delivery Verification" | |
| ] | |
| subject = custom_subject or random.choice(subjects) | |
| body = f""" | |
| <html> | |
| <body> | |
| <h2>Test Email</h2> | |
| <p>This is a test message generated by the example client at {datetime.now().isoformat()}</p> | |
| <p><strong>Message ID:</strong> {message_id}</p> | |
| <p>This message demonstrates the integration pattern with genro-mail-proxy:</p> | |
| <ol> | |
| <li>Message created in local database (your app's DB)</li> | |
| <li>Submitted to mail service via REST API</li> | |
| <li>Immediate dispatch triggered (optional)</li> | |
| <li>Delivery report received via proxy_sync endpoint</li> | |
| </ol> | |
| <p style="color: #666; font-size: 12px;"> | |
| Generated by example_client.py | |
| </p> | |
| </body> | |
| </html> | |
| """ | |
| # Store in local database FIRST | |
| conn = sqlite3.connect(self.db_path) | |
| conn.execute(""" | |
| INSERT INTO outbound_emails (id, recipient, subject, body, created_at, status) | |
| VALUES (?, ?, ?, ?, ?, 'pending') | |
| """, (message_id, self.test_recipient, subject, body, int(time.time()))) | |
| conn.commit() | |
| conn.close() | |
| logger.info(f"Created message {message_id} in local database") | |
| msg = { | |
| 'id': message_id, | |
| 'to': self.test_recipient, | |
| 'from': self.test_sender, | |
| 'from_name': self.test_sender_name, | |
| 'subject': subject, | |
| 'body': body, | |
| 'html': True | |
| } | |
| # Add account_id if configured | |
| if self.account_id: | |
| msg['account_id'] = self.account_id | |
| return msg | |
| async def submit_to_mail_service(self, messages: list[dict]) -> dict: | |
| """ | |
| Step 2: Submit message(s) to mail service. | |
| This uses the /commands/add-messages endpoint to hand off email | |
| delivery responsibility to the mail service. | |
| """ | |
| async with aiohttp.ClientSession() as session: | |
| headers = { | |
| 'X-API-Token': self.api_token, | |
| 'Content-Type': 'application/json' | |
| } | |
| url = f"{self.mail_service_url}/commands/add-messages" | |
| try: | |
| async with session.post(url, json={'messages': messages}, headers=headers) as resp: | |
| if resp.status != 200: | |
| error_text = await resp.text() | |
| raise HTTPException(status_code=resp.status, detail=f"Mail service error: {error_text}") | |
| result = await resp.json() | |
| logger.info(f"Submitted {len(messages)} message(s) to mail service: {result}") | |
| # Update local database | |
| conn = sqlite3.connect(self.db_path) | |
| for msg in messages: | |
| conn.execute(""" | |
| UPDATE outbound_emails | |
| SET submitted_at = ?, status = 'submitted' | |
| WHERE id = ? | |
| """, (int(time.time()), msg['id'])) | |
| conn.commit() | |
| conn.close() | |
| return result | |
| except aiohttp.ClientError as e: | |
| logger.error(f"Failed to submit to mail service: {e}") | |
| raise HTTPException(status_code=503, detail=f"Mail service unavailable: {str(e)}") | |
| async def trigger_immediate_dispatch(self): | |
| """ | |
| Step 3: Trigger immediate dispatch (optional, best-effort). | |
| This is the "run-now" trigger that wakes up the SMTP dispatch loop. | |
| If this fails, the polling mechanism will still process the message. | |
| """ | |
| async with aiohttp.ClientSession() as session: | |
| headers = {'X-API-Token': self.api_token} | |
| url = f"{self.mail_service_url}/commands/run-now" | |
| try: | |
| async with session.post(url, headers=headers) as resp: | |
| if resp.status == 200: | |
| logger.info("Triggered immediate dispatch") | |
| else: | |
| logger.warning(f"Failed to trigger immediate dispatch: {resp.status}") | |
| except aiohttp.ClientError as e: | |
| logger.warning(f"Could not trigger immediate dispatch (non-fatal): {e}") | |
| def get_pending_messages(self) -> list[dict]: | |
| """Get messages from local database that haven't been delivered yet.""" | |
| conn = sqlite3.connect(self.db_path) | |
| cursor = conn.execute(""" | |
| SELECT id, recipient, subject, status, created_at, submitted_at | |
| FROM outbound_emails | |
| WHERE status IN ('pending', 'submitted') | |
| ORDER BY created_at DESC | |
| """) | |
| messages = [] | |
| for row in cursor.fetchall(): | |
| messages.append({ | |
| 'id': row[0], | |
| 'recipient': row[1], | |
| 'subject': row[2], | |
| 'status': row[3], | |
| 'created_at': datetime.fromtimestamp(row[4]).isoformat(), | |
| 'submitted_at': datetime.fromtimestamp(row[5]).isoformat() if row[5] else None | |
| }) | |
| conn.close() | |
| return messages | |
| def get_message_stats(self) -> dict: | |
| """Get statistics about messages in local database.""" | |
| conn = sqlite3.connect(self.db_path) | |
| cursor = conn.execute(""" | |
| SELECT | |
| COUNT(*) as total, | |
| SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending, | |
| SUM(CASE WHEN status = 'submitted' THEN 1 ELSE 0 END) as submitted, | |
| SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) as delivered, | |
| SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed | |
| FROM outbound_emails | |
| """) | |
| row = cursor.fetchone() | |
| conn.close() | |
| return { | |
| 'total': row[0], | |
| 'pending': row[1] or 0, | |
| 'submitted': row[2] or 0, | |
| 'delivered': row[3] or 0, | |
| 'failed': row[4] or 0 | |
| } | |
| # Initialize FastAPI app | |
| app = FastAPI( | |
| title="Example Mail Service Client", | |
| description="Demonstrates integration with genro-mail-proxy", | |
| version="1.0.0" | |
| ) | |
| # Initialize client | |
| client = ExampleClient() | |
| async def root(): | |
| """Welcome endpoint with usage instructions.""" | |
| return { | |
| 'service': 'Example Mail Service Client', | |
| 'description': 'Demonstrates integration with genro-mail-proxy', | |
| 'endpoints': { | |
| '/send-test-email': 'POST - Generate and send test email(s)', | |
| '/messages': 'GET - List pending messages', | |
| '/stats': 'GET - Get message statistics', | |
| '/proxy_sync': 'POST - Receive delivery reports from mail service' | |
| }, | |
| 'usage': { | |
| 'send_single': 'curl -X POST http://localhost:8081/send-test-email', | |
| 'send_multiple': 'curl -X POST http://localhost:8081/send-test-email?count=5', | |
| 'view_stats': 'curl http://localhost:8081/stats' | |
| } | |
| } | |
| async def send_test_email( | |
| count: int = Query(1, ge=1, le=100, description="Number of test emails to send"), | |
| subject: Optional[str] = Query(None, description="Custom subject line") | |
| ): | |
| """ | |
| Generate and send test email(s). | |
| This endpoint demonstrates the complete integration flow: | |
| 1. Creates message(s) in local database | |
| 2. Submits to mail service | |
| 3. Triggers immediate dispatch | |
| Query Parameters: | |
| - count: Number of emails to send (1-100, default 1) | |
| - subject: Custom subject line (optional) | |
| """ | |
| try: | |
| # Step 1: Create messages in local database | |
| messages = [] | |
| for i in range(count): | |
| custom_subj = f"{subject} ({i+1}/{count})" if subject and count > 1 else subject | |
| msg = await client.create_test_message(custom_subject=custom_subj) | |
| messages.append(msg) | |
| # Step 2: Submit to mail service | |
| result = await client.submit_to_mail_service(messages) | |
| # Step 3: Trigger immediate dispatch (best-effort) | |
| await client.trigger_immediate_dispatch() | |
| return { | |
| 'status': 'success', | |
| 'message': f'Successfully queued {count} test email(s)', | |
| 'messages': [msg['id'] for msg in messages], | |
| 'mail_service_response': result, | |
| 'note': 'Check /stats endpoint to monitor delivery status' | |
| } | |
| except Exception as e: | |
| logger.error(f"Error sending test email: {e}") | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def list_messages(): | |
| """List pending messages from local database.""" | |
| try: | |
| messages = client.get_pending_messages() | |
| return { | |
| 'status': 'success', | |
| 'count': len(messages), | |
| 'messages': messages | |
| } | |
| except Exception as e: | |
| logger.error(f"Error listing messages: {e}") | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def get_stats(): | |
| """Get message statistics.""" | |
| try: | |
| stats = client.get_message_stats() | |
| return { | |
| 'status': 'success', | |
| 'statistics': stats | |
| } | |
| except Exception as e: | |
| logger.error(f"Error getting stats: {e}") | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def proxy_sync(request: Request): | |
| """ | |
| Delivery report endpoint (called by mail service). | |
| This receives delivery confirmations from genro-mail-proxy. | |
| The path matches the Genropy convention for compatibility. | |
| """ | |
| try: | |
| data = await request.json() | |
| reports = data.get('reports', []) | |
| logger.info(f"Received {len(reports)} delivery report(s)") | |
| # Update local database with delivery status | |
| conn = sqlite3.connect(client.db_path) | |
| for report in reports: | |
| msg_id = report.get('id') | |
| status = report.get('status') | |
| error = report.get('error') | |
| if status == 'sent': | |
| conn.execute(""" | |
| UPDATE outbound_emails | |
| SET delivered_at = ?, status = 'delivered' | |
| WHERE id = ? | |
| """, (int(time.time()), msg_id)) | |
| logger.info(f"Message {msg_id} marked as delivered") | |
| elif status == 'error': | |
| conn.execute(""" | |
| UPDATE outbound_emails | |
| SET error = ?, status = 'failed' | |
| WHERE id = ? | |
| """, (error, msg_id)) | |
| logger.warning(f"Message {msg_id} failed: {error}") | |
| conn.commit() | |
| conn.close() | |
| # Acknowledge receipt | |
| return { | |
| 'status': 'ok', | |
| 'processed': len(reports) | |
| } | |
| except Exception as e: | |
| logger.error(f"Error processing delivery reports: {e}") | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| if __name__ == "__main__": | |
| logger.info("Starting example client server...") | |
| logger.info(f"Test emails will be sent to: {client.test_recipient}") | |
| logger.info(f"Server listening on port: {client.port}") | |
| logger.info("") | |
| logger.info("Try these commands:") | |
| logger.info(f" curl -X POST http://localhost:{client.port}/send-test-email") | |
| logger.info(f" curl -X POST http://localhost:{client.port}/send-test-email?count=5") | |
| logger.info(f" curl http://localhost:{client.port}/stats") | |
| logger.info("") | |
| uvicorn.run(app, host="0.0.0.0", port=client.port, log_level="info") | |
Xet Storage Details
- Size:
- 16 kB
- Xet hash:
- acab48a040b93c4fff7641f12400ce7a2e8afa537529178f6dafee0cc03710ab
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.