Python
Python integration examples for Keplers Mail Service
Send emails using Python with both REST API and SMTP approaches.
Installation
pip install requestsBasic Setup
# .env
KEPLERS_API_KEY=kms_your_api_key.live_...REST API Integration
Basic Client
import requests
import os
class KeplersMailClient:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = 'https://api.keplars.com'
self.session = requests.Session()
self.session.headers.update({
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
})
def send_email(self, email_data):
try:
response = self.session.post(
f'{self.base_url}/api/v1/send-email/queue',
json=email_data
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
raise Exception(f'Failed to send email: {str(e)}')
def send_instant_email(self, email_data):
try:
response = self.session.post(
f'{self.base_url}/api/v1/send-email/instant',
json=email_data
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
raise Exception(f'Failed to send instant email: {str(e)}')
def create_client():
api_key = os.getenv('KEPLERS_API_KEY')
if not api_key:
raise ValueError('KEPLERS_API_KEY environment variable is required')
return KeplersMailClient(api_key)Usage Examples
client = create_client()
def send_welcome_email(user_email, user_name):
try:
email_data = {
'to': [user_email],
'subject': f'Welcome {user_name}!',
'body': f'''
<h1>Welcome {user_name}!</h1>
<p>Thank you for joining our platform.</p>
<a href="https://app.example.com/dashboard">Get Started</a>
''',
'is_html': True
}
result = client.send_email(email_data)
print(f'Email sent: {result}')
return result
except Exception as e:
print(f'Failed to send email: {str(e)}')
raise
def send_verification_email(user_email, verification_code):
try:
email_data = {
'to': [user_email],
'subject': 'Verify Your Email',
'body': f'Your verification code: {verification_code}',
'is_html': False
}
result = client.send_instant_email(email_data)
print(f'Verification email sent: {result}')
return result
except Exception as e:
print(f'Failed to send verification email: {str(e)}')
raise
# Usage
send_welcome_email('[email protected]', 'John')
import secrets
verification_code = secrets.token_hex(3).upper()
send_verification_email('[email protected]', verification_code)Flask Integration
from flask import Flask, request, jsonify
app = Flask(__name__)
client = create_client()
@app.route('/api/send-email', methods=['POST'])
def send_email():
try:
data = request.get_json()
email = data.get('email')
name = data.get('name')
email_data = {
'to': [email],
'subject': f'Welcome {name}!',
'body': f'<h1>Welcome {name}!</h1>',
'is_html': True
}
result = client.send_email(email_data)
return jsonify({'success': True, 'data': result})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/verification', methods=['POST'])
def send_verification():
try:
data = request.get_json()
email = data.get('email')
import secrets
code = secrets.token_hex(3).upper()
email_data = {
'to': [email],
'subject': 'Verification Code',
'body': f'Your code: {code}',
'is_html': False
}
result = client.send_instant_email(email_data)
return jsonify({'success': True, 'data': result, 'code': code})
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(debug=True)SMTP Integration
Installation
pip install secure-smtplibSMTP Client
import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import os
class KeplersEmailSMTPClient:
def __init__(self, smtp_config):
self.config = smtp_config
self.server = None
def __enter__(self):
self.connect()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.disconnect()
def connect(self):
try:
self.server = smtplib.SMTP('smtp.keplars.com', 587)
self.server.starttls()
self.server.login(self.config['username'], self.config['password'])
except Exception as e:
raise Exception(f"SMTP connection failed: {str(e)}")
def disconnect(self):
if self.server:
try:
self.server.quit()
except:
pass
finally:
self.server = None
def send_email(self, to, subject, body, is_html=False):
try:
if not self.server:
self.connect()
msg = MIMEMultipart() if is_html else MIMEText(body, 'plain')
if is_html and isinstance(msg, MIMEMultipart):
text_part = MIMEText(body, 'plain')
html_part = MIMEText(body, 'html')
msg.attach(text_part)
msg.attach(html_part)
msg['Subject'] = subject
msg['To'] = to if isinstance(to, str) else ', '.join(to)
to_list = [to] if isinstance(to, str) else to
self.server.sendmail('[email protected]', to_list, msg.as_string())
return {
'success': True,
'data': {'status': 'sent', 'method': 'smtp'}
}
except Exception as e:
raise Exception(f"SMTP send failed: {str(e)}")
def create_smtp_client():
config = {
'username': os.getenv('KEPLERS_SMTP_USERNAME'),
'password': os.getenv('KEPLERS_SMTP_PASSWORD')
}
if not config['username'] or not config['password']:
raise ValueError('SMTP credentials are required')
return KeplersEmailSMTPClient(config)SMTP Usage
smtp_client = create_smtp_client()
def send_email_via_smtp(user_email, subject, body, is_html=True):
try:
with smtp_client as client:
result = client.send_email(
to=user_email,
subject=subject,
body=body,
is_html=is_html
)
print(f"SMTP email sent: {result}")
return result
except Exception as e:
print(f"SMTP send failed: {str(e)}")
raise
# Usage
send_email_via_smtp(
'[email protected]',
'Welcome!',
'<h1>Welcome to our platform!</h1>'
)Choose REST API for advanced features or SMTP for traditional email client integration.