Try Live
Add Docs
Rankings
Pricing
Docs
Install
Theme
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Mailtrap Python Client
https://github.com/mailtrap/mailtrap-python
Admin
This Python package provides an official client for the Mailtrap API, enabling quick integration of
...
Tokens:
11,490
Snippets:
44
Trust Score:
5.7
Update:
5 months ago
Context
Skills
Chat
Benchmark
87.8
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Mailtrap Python Client Mailtrap is an official Python client for the Mailtrap API that enables developers to integrate email sending, testing, and management capabilities into their Python applications. The library provides a unified interface to interact with Mailtrap's transactional email delivery service, email sandbox testing environment, and comprehensive contact management system. This SDK supports both production email sending (transactional and bulk streams) and sandbox testing modes, allowing developers to safely test email functionality before deploying to production. It offers complete access to Mailtrap's REST API including email sending, template management, contact list operations, inbox management, suppression handling, account administration, billing information, and access control. The library is built with modern Python practices, uses Pydantic for data validation, and provides both synchronous API calls with type-safe models and flexible dictionary responses. ## Send Email Send a transactional email with basic text content through Mailtrap's production sending API. ```python import mailtrap as mt # Initialize client with API token client = mt.MailtrapClient(token="your_api_token_here") # Create and send email mail = mt.Mail( sender=mt.Address(email="sender@example.com", name="John Smith"), to=[mt.Address(email="recipient@example.com")], subject="You are awesome!", text="Congrats for sending test email with Mailtrap!", ) # Send and get response response = client.send(mail) # Returns: {"success": True, "message_ids": ["5162954175"]} ``` ## Send Email with HTML and Attachments Send a richly formatted email with HTML content, inline images, custom headers, and file attachments. ```python import base64 import mailtrap as mt from pathlib import Path client = mt.MailtrapClient(token="your_api_token_here") # Read image file for attachment welcome_image = Path("welcome.png").read_bytes() mail = mt.Mail( sender=mt.Address(email="mailtrap@example.com", name="Mailtrap Test"), to=[mt.Address(email="recipient@example.com", name="Recipient Name")], cc=[mt.Address(email="cc@email.com", name="Copy to")], bcc=[mt.Address(email="bcc@email.com", name="Hidden Recipient")], subject="You are awesome!", text="Congrats for sending test email with Mailtrap!", html=""" <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body style="font-family: sans-serif;"> <div style="display: block; margin: auto; max-width: 600px;"> <h1 style="font-size: 18px; font-weight: bold; margin-top: 20px"> Congrats for sending test email with Mailtrap! </h1> <p>Inspect it using the tabs you see above.</p> <img alt="Inspect with Tabs" src="cid:welcome.png" style="width: 100%;"> <p>Now send your email using our fake SMTP server!</p> </div> </body> </html> """, category="Test", attachments=[ mt.Attachment( content=base64.b64encode(welcome_image), filename="welcome.png", disposition=mt.Disposition.INLINE, mimetype="image/png", content_id="welcome.png", ) ], headers={"X-MT-Header": "Custom header"}, custom_variables={"year": 2023}, ) response = client.send(mail) # Returns: {"success": True, "message_ids": ["5162954176"]} ``` ## Send Email Using Template Send an email using a pre-defined template with variable substitution for personalized content. ```python import mailtrap as mt client = mt.MailtrapClient(token="your_api_token_here") mail = mt.MailFromTemplate( sender=mt.Address(email="mailtrap@example.com", name="Mailtrap Test"), to=[mt.Address(email="recipient@example.com")], template_uuid="2f45b0aa-bbed-432f-95e4-e145e1965ba2", template_variables={ "company_info_name": "Test_Company_info_name", "name": "John Doe", "company_info_address": "123 Main Street", "company_info_city": "New York", "company_info_zip_code": "10001", "company_info_country": "USA", }, ) response = client.send(mail) # Returns: {"success": True, "message_ids": ["5162954177"]} ``` ## Batch Send Emails Send multiple emails with shared base content but different recipients efficiently in a single API call. ```python import mailtrap as mt client = mt.MailtrapClient(token="your_api_token_here") # Define base email content shared by all recipients batch_mail = mt.BatchSendEmailParams( base=mt.BatchMail( sender=mt.Address(email="sender@example.com", name="Sender Name"), subject="You are awesome!", text="Congrats for sending test email with Mailtrap!", category="Integration Test", ), # Define individual recipients requests=[ mt.BatchEmailRequest( to=[mt.Address(email="recipient1@example.com")], ), mt.BatchEmailRequest( to=[mt.Address(email="recipient2@example.com")], ), mt.BatchEmailRequest( to=[mt.Address(email="recipient3@example.com")], ), ], ) response = client.batch_send(batch_mail) # Returns: { # "success": True, # "message_ids": ["5162954178", "5162954179", "5162954180"], # "errors": [] # } ``` ## Switch Between Sandbox and Production Toggle between sandbox testing mode and production sending using environment variables for easy deployment management. ```python import os import mailtrap as mt # Configuration from environment API_KEY = os.environ["MAILTRAP_API_KEY"] IS_SANDBOX = os.environ.get("MAILTRAP_USE_SANDBOX", "true").lower() == "true" INBOX_ID = os.environ.get("MAILTRAP_INBOX_ID") # Only needed for sandbox # Initialize client with appropriate mode client = mt.MailtrapClient( token=API_KEY, sandbox=IS_SANDBOX, inbox_id=INBOX_ID, # Ignored if sandbox=False ) mail = mt.Mail( sender=mt.Address(email="sender@example.com", name="John Smith"), to=[mt.Address(email="recipient@example.com")], subject="You are awesome!", text="Congrats for sending test email with Mailtrap!", ) response = client.send(mail) # In sandbox: email goes to test inbox # In production: email sends to actual recipients ``` ## Use Bulk Sending Mode Configure the client for high-volume bulk email sending with optimized delivery for marketing campaigns. ```python import mailtrap as mt # Initialize client for bulk sending client = mt.MailtrapClient(token="your_api_token_here", bulk=True) mail = mt.Mail( sender=mt.Address(email="marketing@example.com", name="Marketing Team"), to=[mt.Address(email="recipient@example.com")], subject="Monthly Newsletter", text="Check out our latest updates!", ) response = client.send(mail) # Sends via bulk stream for high-volume sending ``` ## Manage Contacts Create, retrieve, update, and delete contacts in your Mailtrap contact database with custom field support. ```python import mailtrap as mt client = mt.MailtrapClient( token="your_api_token_here", account_id="your_account_id" ) contacts_api = client.contacts_api.contacts # Create a new contact created_contact = contacts_api.create( mt.CreateContactParams( email="user@example.com", fields={ "first_name": "John", "last_name": "Doe", }, list_ids=[123, 456], # Add to specific lists ) ) # Returns: Contact(id="123abc", email="user@example.com", ...) # Get contact by ID or email contact = contacts_api.get_by_id("123abc") # or contact = contacts_api.get_by_id("user@example.com") # Update contact information updated_contact = contacts_api.update( "123abc", mt.UpdateContactParams( email="newemail@example.com", fields={"first_name": "Jane"}, list_ids_included=[789], list_ids_excluded=[123], unsubscribed=False, ) ) # Delete contact deleted = contacts_api.delete("123abc") # Returns: DeletedObject(id="123abc", deleted=True) ``` ## Manage Contact Lists Create and manage contact lists for organizing recipients into segments for targeted campaigns. ```python import mailtrap as mt client = mt.MailtrapClient( token="your_api_token_here", account_id="your_account_id" ) contact_lists_api = client.contacts_api.contact_lists # Create a new contact list new_list = contact_lists_api.create( mt.ContactListParams(name="Newsletter Subscribers") ) # Returns: ContactList(id=123, name="Newsletter Subscribers", ...) # Get all contact lists all_lists = contact_lists_api.get_list() # Returns: [ContactList(...), ContactList(...), ...] # Get specific contact list contact_list = contact_lists_api.get_by_id(123) # Update contact list name updated_list = contact_lists_api.update( 123, mt.ContactListParams(name="Premium Subscribers") ) # Delete contact list deleted = contact_lists_api.delete(123) # Returns: DeletedObject(id=123, deleted=True) ``` ## Manage Contact Fields Create and manage custom fields for storing additional contact information and segmentation. ```python import mailtrap as mt client = mt.MailtrapClient( token="your_api_token_here", account_id="your_account_id" ) contact_fields_api = client.contacts_api.contact_fields # Create a new contact field new_field = contact_fields_api.create( mt.CreateContactFieldParams( name="Company Size", data_type="string", merge_tag="COMPANY_SIZE", ) ) # Returns: ContactField(id=123, name="Company Size", ...) # List all contact fields all_fields = contact_fields_api.get_list() # Returns: [ContactField(...), ContactField(...), ...] # Get specific contact field field = contact_fields_api.get_by_id(123) # Update contact field updated_field = contact_fields_api.update( 123, mt.UpdateContactFieldParams( name="Company Employee Count", merge_tag="EMPLOYEE_COUNT", ) ) # Delete contact field deleted = contact_fields_api.delete(123) # Returns: DeletedObject(id=123, deleted=True) ``` ## Import Contacts Bulk import contacts into your Mailtrap account with custom fields and list assignments. ```python import mailtrap as mt client = mt.MailtrapClient( token="your_api_token_here", account_id="your_account_id" ) contact_imports_api = client.contacts_api.contact_imports # Import multiple contacts at once contact_import = contact_imports_api.import_contacts( contacts=[ mt.ImportContactParams( email="user1@example.com", fields={"first_name": "John", "last_name": "Doe"}, ), mt.ImportContactParams( email="user2@example.com", fields={"first_name": "Jane", "last_name": "Smith"}, ), ] ) # Returns: ContactImport(id=456, status="pending", ...) # Check import status import_status = contact_imports_api.get_by_id(456) # Returns: ContactImport(id=456, status="completed", ...) ``` ## Export Contacts Export contacts with filters for backup or analysis purposes. ```python import mailtrap as mt client = mt.MailtrapClient( token="your_api_token_here", account_id="your_account_id" ) contact_exports_api = client.contacts_api.contact_exports # Create contact export with filters contact_export = contact_exports_api.create( contact_exports_params=mt.CreateContactExportParams( filters=[ mt.ContactExportFilter( name="list_id", operator="equal", value=[123, 456], ) ] ) ) # Returns: ContactExportDetail(id=789, status="pending", ...) # Check export status and download link export_status = contact_exports_api.get_by_id(789) # Returns: ContactExportDetail(id=789, status="completed", download_url="...", ...) ``` ## Track Contact Events Create custom events to track contact behavior and interactions with your application. ```python import mailtrap as mt client = mt.MailtrapClient( token="your_api_token_here", account_id="your_account_id" ) contact_events_api = client.contacts_api.contact_events # Create a contact event contact_event = contact_events_api.create( contact_identifier="01988623-832f-79df-8aae-a480f8ff7249", contact_event_params=mt.ContactEventParams( name="UserLogin", params={ "user_id": 101, "user_name": "John Smith", "is_active": True, "login_time": "2024-01-15T10:30:00Z", }, ), ) # Returns: ContactEvent(id="abc123", name="UserLogin", ...) ``` ## Manage Email Templates Create, retrieve, update, and delete email templates for reusable email designs and content. ```python import mailtrap as mt client = mt.MailtrapClient( token="your_api_token_here", account_id="your_account_id" ) templates_api = client.email_templates_api.templates # Create a new template template = templates_api.create( mt.CreateEmailTemplateParams( name="Welcome Email", subject="Welcome to {{company_name}}!", category="onboarding", body_text="Hello {{name}}, welcome to our platform!", body_html="<h1>Hello {{name}}</h1><p>Welcome to our platform!</p>", ) ) # Returns: EmailTemplate(uuid="2f45b0aa-...", name="Welcome Email", ...) # List all templates all_templates = templates_api.get_list() # Get specific template template = templates_api.get_by_id("2f45b0aa-bbed-432f-95e4-e145e1965ba2") # Update template updated_template = templates_api.update( "2f45b0aa-bbed-432f-95e4-e145e1965ba2", mt.UpdateEmailTemplateParams( name="Updated Welcome Email", subject="Welcome aboard, {{name}}!", ) ) # Delete template deleted = templates_api.delete("2f45b0aa-bbed-432f-95e4-e145e1965ba2") # Returns: DeletedObject(id="2f45b0aa-...", deleted=True) ``` ## Manage Sandbox Inboxes Create and manage test inboxes in the Mailtrap sandbox environment for email testing. ```python import mailtrap as mt client = mt.MailtrapClient( token="your_api_token_here", account_id="your_account_id" ) inboxes_api = client.testing_api.inboxes # List all inboxes inboxes = inboxes_api.get_list() # Returns: [Inbox(id=123, name="Test Inbox", ...), ...] # Create a new inbox new_inbox = inboxes_api.create( project_id=456, inbox_params=mt.CreateInboxParams(name="QA Testing Inbox") ) # Returns: Inbox(id=789, name="QA Testing Inbox", ...) # Get inbox details inbox = inboxes_api.get_by_id(789) # Update inbox settings updated_inbox = inboxes_api.update( 789, mt.UpdateInboxParams( name="Staging Inbox", email_username="staging-test" ) ) # Clean all messages from inbox cleaned_inbox = inboxes_api.clean(789) # Mark all messages as read read_inbox = inboxes_api.mark_as_read(789) # Reset SMTP credentials reset_inbox = inboxes_api.reset_credentials(789) # Delete inbox deleted = inboxes_api.delete(789) ``` ## Manage Sandbox Projects Organize sandbox inboxes into projects for better test environment management. ```python import mailtrap as mt client = mt.MailtrapClient( token="your_api_token_here", account_id="your_account_id" ) projects_api = client.testing_api.projects # List all projects projects = projects_api.get_list() # Returns: [Project(id=123, name="Development", ...), ...] # Create a new project new_project = projects_api.create( project_params=mt.ProjectParams(name="Staging Environment") ) # Returns: Project(id=456, name="Staging Environment", ...) # Get project details project = projects_api.get_by_id(456) # Update project name updated_project = projects_api.update( 456, mt.ProjectParams(name="QA Environment") ) # Delete project deleted = projects_api.delete(456) ``` ## Manage Sandbox Messages Retrieve, inspect, and manipulate test emails received in sandbox inboxes. ```python import mailtrap as mt client = mt.MailtrapClient( token="your_api_token_here", account_id="your_account_id" ) messages_api = client.testing_api.messages # List messages in an inbox messages = messages_api.get_list( inbox_id=123, search="subject:welcome", # Optional search filter page=1, ) # Returns: [EmailMessage(...), EmailMessage(...), ...] # Get specific message message = messages_api.show_message(inbox_id=123, message_id=456) # Returns: EmailMessage(id=456, subject="Welcome!", ...) # Update message status updated_message = messages_api.update( inbox_id=123, message_id=456, message_params=mt.UpdateEmailMessageParams(is_read=True) ) # Forward message to external email forwarded = messages_api.forward( inbox_id=123, message_id=456, email="developer@company.com" ) # Returns: ForwardedMessage(success=True) # Get spam analysis report spam_report = messages_api.get_spam_report(inbox_id=123, message_id=456) # Returns: SpamReport(score=0.1, rules=[...]) # Get HTML email analysis html_analysis = messages_api.get_html_analysis(inbox_id=123, message_id=456) # Returns: AnalysisReport(errors=[...], warnings=[...]) # Get raw message content raw_message = messages_api.get_raw_message(inbox_id=123, message_id=456) html_source = messages_api.get_html_source(inbox_id=123, message_id=456) text_content = messages_api.get_text_message(inbox_id=123, message_id=456) # Download message as EML file eml_content = messages_api.get_message_as_eml(inbox_id=123, message_id=456) # Delete message deleted_message = messages_api.delete(inbox_id=123, message_id=456) ``` ## Manage Message Attachments Retrieve attachments from test emails in sandbox inboxes. ```python import mailtrap as mt client = mt.MailtrapClient( token="your_api_token_here", account_id="your_account_id" ) attachments_api = client.testing_api.attachments # List all attachments for a message attachments = attachments_api.get_list(inbox_id=123, message_id=456) # Returns: [Attachment(id=789, filename="document.pdf", ...), ...] # Get specific attachment attachment = attachments_api.get( inbox_id=123, message_id=456, attachment_id=789, ) # Returns: Attachment(id=789, filename="document.pdf", content=..., ...) ``` ## Manage Suppressions View and manage email addresses that are suppressed from receiving emails due to bounces or unsubscribes. ```python import mailtrap as mt client = mt.MailtrapClient( token="your_api_token_here", account_id="your_account_id" ) suppressions_api = client.suppressions_api.suppressions # List all suppressions all_suppressions = suppressions_api.get_list() # Returns: [Suppression(id="abc123", email="bounced@example.com", ...), ...] # Search for specific email specific_suppressions = suppressions_api.get_list(email="bounced@example.com") # Delete suppression to allow sending again deleted = suppressions_api.delete("abc123") # Returns: Suppression(id="abc123", deleted=True) ``` ## List Accounts Retrieve all Mailtrap accounts accessible with the current API token for multi-account management. ```python import mailtrap as mt client = mt.MailtrapClient(token="your_api_token_here") accounts_api = client.general_api.accounts # Get all accessible accounts accounts = accounts_api.get_list() # Returns: [ # Account(id="123", name="Company Account", ...), # Account(id="456", name="Personal Account", ...), # ] # Use account ID for subsequent operations account_id = accounts[0].id ``` ## Manage Account Accesses List and remove user access permissions for your Mailtrap accounts. ```python import mailtrap as mt client = mt.MailtrapClient(token="your_api_token_here") account_accesses_api = client.general_api.account_accesses # List all account accesses accesses = account_accesses_api.get_list(account_id=123) # Returns: [AccountAccess(id=456, user_email="user@example.com", ...), ...] # Delete an account access deleted = account_accesses_api.delete( account_id=123, account_access_id=456, ) # Returns: DeletedObject(id=456, deleted=True) ``` ## Manage Permissions View and update permission levels for account resources and user access control. ```python import mailtrap as mt client = mt.MailtrapClient(token="your_api_token_here") permissions_api = client.general_api.permissions # Get all permission resources for an account resources = permissions_api.get_resources(account_id=123) # Returns: [PermissionResource(id=789, type="inbox", ...), ...] # Bulk update permissions for a user updated = permissions_api.bulk_permissions_update( account_id=123, account_access_id=456, permissions=[ mt.PermissionResourceParams( resource_id=789, resource_type="inbox", access_level="viewer", ), mt.PermissionResourceParams( resource_id=790, resource_type="project", access_level="editor", ), ], ) # Returns: UpdatePermissionsResponse(success=True) ``` ## Get Billing Information Retrieve current billing cycle usage information for your Mailtrap account. ```python import mailtrap as mt client = mt.MailtrapClient(token="your_api_token_here") billing_api = client.general_api.billing # Get current billing cycle usage usage = billing_api.get_current_billing_usage(account_id=123) # Returns: BillingCycleUsage( # emails_sent=1250, # emails_limit=10000, # cycle_start="2024-01-01", # cycle_end="2024-01-31", # ... # ) ``` ## Alternative Sending API Usage Access the sending API directly for model-based responses instead of dictionary responses. ```python import mailtrap as mt client = mt.MailtrapClient(token="your_api_token_here") sending_api = client.sending_api mail = mt.Mail( sender=mt.Address(email="sender@example.com", name="John Smith"), to=[mt.Address(email="recipient@example.com")], subject="You are awesome!", text="Congrats for sending test email with Mailtrap!", ) # Using sending_api directly returns Pydantic model response = sending_api.send(mail) # Returns: SendingMailResponse(success=True, message_ids=["5162955057"]) # Access fields as attributes if response.success: print(f"Sent with IDs: {response.message_ids}") ``` ## Summary Mailtrap Python client provides a complete solution for email operations in modern Python applications. The primary use cases include transactional email sending for user notifications and alerts, bulk email campaigns for marketing and newsletters, pre-production email testing in sandbox environments, contact and mailing list management for segmented communications, and programmatic access to email templates for consistent branding. The library supports both simple single-recipient messages and complex batch operations with thousands of recipients, making it suitable for applications ranging from small startups to enterprise-scale email infrastructure. Advanced features include contact field customization for enhanced segmentation, bulk contact import/export operations, event tracking for behavioral analytics, account access management for team collaboration, and detailed billing information for usage monitoring. The integration patterns are straightforward and flexible. Initialize a MailtrapClient with your API token and configure it for your specific use case (production, sandbox, or bulk sending). Access specialized API endpoints through client properties like sending_api, contacts_api, testing_api, email_templates_api, suppressions_api, and general_api. All operations follow consistent patterns with parameter objects for complex inputs and strongly-typed response models for reliable data handling. The library supports both dictionary-based responses for simple use cases and Pydantic model responses for applications requiring strict type safety. Environment-based configuration enables seamless transitions between development, staging, and production environments without code changes. The contacts API provides comprehensive management capabilities including custom fields, imports, exports, and event tracking for sophisticated contact relationship management.