├── .github ├── pull_request_template.md └── workflows │ └── main.yml ├── .gitignore ├── .pre-commit-config.yaml ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── LICENSE.txt ├── README.md ├── mailtrap ├── __init__.py ├── client.py ├── exceptions.py └── mail │ ├── __init__.py │ ├── address.py │ ├── attachment.py │ ├── base.py │ ├── base_entity.py │ ├── from_template.py │ └── mail.py ├── pyproject.toml ├── requirements.test.txt ├── requirements.txt ├── tests ├── __init__.py └── unit │ ├── __init__.py │ ├── mail │ ├── __init__.py │ ├── test_address.py │ ├── test_attachment.py │ ├── test_from_template.py │ └── test_mail.py │ ├── test_client.py │ └── test_exceptions.py └── tox.ini /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ## Motivation 2 | 3 | 4 | ## Changes 5 | 6 | - Change 1 7 | - Change 2 8 | 9 | ## How to test 10 | 11 | - [ ] Test 1 12 | - [ ] Test 2 13 | 14 | ## Images and GIFs 15 | 16 | | Before | After | 17 | |--------|--------| 18 | | link1 | link2 | 19 | | link3 | link4 | 20 | | link5 | link6 | 21 | | link7 | link8 | 22 | | link9 | link10 | 23 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Tests and checks 2 | 3 | on: push 4 | 5 | permissions: 6 | contents: read 7 | 8 | jobs: 9 | check: 10 | name: Test python${{ matrix.python }} on ${{ matrix.os }} 11 | runs-on: ${{ matrix.os }} 12 | strategy: 13 | matrix: 14 | os: 15 | - "ubuntu-latest" 16 | - "windows-latest" 17 | - "macos-latest" 18 | python: 19 | - "3.9" 20 | - "3.10" 21 | - "3.11" 22 | - "3.12" 23 | - "3.13" 24 | steps: 25 | - uses: actions/checkout@v4 26 | - name: Setup python 27 | uses: actions/setup-python@v5 28 | with: 29 | python-version: ${{ matrix.python }} 30 | - name: Install tox 31 | run: pip install tox 32 | - name: Run tests 33 | run: tox -e py${{ matrix.python }} 34 | - name: Run linters 35 | run: tox -e pre-commit 36 | - name: Run type checking 37 | run: tox -e mypy 38 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | 4 | # Distribution / packaging 5 | dist/ 6 | *.egg-info/ 7 | 8 | # IntelliJ's project specific settings 9 | .idea/ 10 | 11 | # mypy 12 | .mypy_cache/ 13 | 14 | # tox 15 | .tox/ 16 | 17 | # tests 18 | .pytest_cache 19 | 20 | # venv 21 | venv 22 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/PyCQA/flake8 3 | rev: 7.2.0 4 | hooks: 5 | - id: flake8 6 | name: Style Guide Enforcement (flake8) 7 | args: 8 | - '--max-line-length=90' 9 | - '--per-file-ignores=__init__.py:F401' 10 | - repo: https://github.com/asottile/pyupgrade 11 | rev: v3.19.0 12 | hooks: 13 | - id: pyupgrade 14 | name: Upgrade syntax for newer versions of the language (pyupgrade) 15 | args: 16 | - '--py39-plus' 17 | - repo: https://github.com/pycqa/isort 18 | rev: 6.0.1 19 | hooks: 20 | - id: isort 21 | name: Reorder Python imports 22 | # - repo: https://github.com/PyCQA/docformatter 23 | # rev: v1.7.5 # incompatible with pre-commit > 4.0.0, but should be fixed in the next release 24 | # hooks: 25 | # - id: docformatter 26 | # name: Formats docstrings 27 | # args: 28 | # - '--in-place ' 29 | - repo: 'https://github.com/pre-commit/pre-commit-hooks' 30 | rev: v5.0.0 31 | hooks: 32 | - id: trailing-whitespace 33 | - id: end-of-file-fixer 34 | - id: check-toml 35 | - repo: https://github.com/python/black 36 | rev: 25.1.0 37 | hooks: 38 | - id: black 39 | name: Uncompromising Code Formatter (black) 40 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [2.1.0] - 2025-05-12 2 | - Add sandbox mode support in MailtrapClient 3 | - It requires inbox_id parameter to be set 4 | - Add bulk mode support in MailtrapClient 5 | - Drop support python 3.6 - 3.8 6 | - Add support for python 3.12 - 3.13 7 | 8 | ## [2.0.1] - 2023-05-18 9 | - Add User-Agent header to all requests 10 | 11 | ## [2.0.0] - 2023-03-11 12 | 13 | - Initial release of the official mailtrap.io API client. 14 | - This release is a completely new library, incompatible with v1. 15 | - Send mails using the new Mailtrap Sending API. 16 | 17 | ## [1.0.1] - 2020-10-03 18 | 19 | - Renamed to [Sendria](https://github.com/msztolcman/sendria). An SMTP server that makes all received mails accessible via a web interface and REST API. 20 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 8 | 9 | ## Our Standards 10 | 11 | Examples of behavior that contributes to a positive environment for our community include: 12 | 13 | * Demonstrating empathy and kindness toward other people 14 | * Being respectful of differing opinions, viewpoints, and experiences 15 | * Giving and gracefully accepting constructive feedback 16 | * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 17 | * Focusing on what is best not just for us as individuals, but for the overall community 18 | 19 | Examples of unacceptable behavior include: 20 | 21 | * The use of sexualized language or imagery, and sexual attention or advances of any kind 22 | * Trolling, insulting or derogatory comments, and personal or political attacks 23 | * Public or private harassment 24 | * Publishing others' private information, such as a physical or email address, without their explicit permission 25 | * Other conduct which could reasonably be considered inappropriate in a professional setting 26 | 27 | ## Enforcement Responsibilities 28 | 29 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. 32 | 33 | ## Scope 34 | 35 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. 36 | 37 | ## Enforcement 38 | 39 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at support@mailtrap.io. All complaints will be reviewed and investigated promptly and fairly. 40 | 41 | All community leaders are obligated to respect the privacy and security of the reporter of any incident. 42 | 43 | ## Enforcement Guidelines 44 | 45 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: 46 | 47 | ### 1. Correction 48 | 49 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. 50 | 51 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. 52 | 53 | ### 2. Warning 54 | 55 | **Community Impact**: A violation through a single incident or series of actions. 56 | 57 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. 58 | 59 | ### 3. Temporary Ban 60 | 61 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. 62 | 63 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. 64 | 65 | ### 4. Permanent Ban 66 | 67 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. 68 | 69 | **Consequence**: A permanent ban from any sort of public interaction within the community. 70 | 71 | ## Attribution 72 | 73 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, 74 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 75 | 76 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). 77 | 78 | [homepage]: https://www.contributor-covenant.org 79 | 80 | For answers to common questions about this code of conduct, see the FAQ at 81 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. 82 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2023 Railsware Products Studio LLC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![test](https://github.com/railsware/mailtrap-python/actions/workflows/main.yml/badge.svg)](https://github.com/railsware/mailtrap-python/actions/workflows/main.yml) 2 | [![PyPI](https://shields.io/pypi/v/mailtrap)](https://pypi.org/project/mailtrap/) 3 | [![downloads](https://shields.io/pypi/dm/mailtrap)](https://pypi.org/project/mailtrap/) 4 | 5 | 6 | # Official Mailtrap Python client 7 | 8 | This Python package offers integration with the [official API](https://api-docs.mailtrap.io/) for [Mailtrap](https://mailtrap.io). 9 | 10 | Quickly add email sending functionality to your Python application with Mailtrap. 11 | 12 | ## Compatibility with previous releases 13 | 14 | Versions of this package up to 1.0.1 were a different, unrelated project, that is now maintained as [Sendria](https://github.com/msztolcman/sendria). To continue using it, see [instructions](#information-for-version-1-users). 15 | 16 | ## Installation 17 | 18 | ### Prerequisites 19 | 20 | - Python version 3.6+ 21 | 22 | ### Install package 23 | 24 | ```text 25 | pip install mailtrap 26 | ``` 27 | 28 | ## Usage 29 | 30 | ### Minimal 31 | 32 | ```python 33 | import mailtrap as mt 34 | 35 | # create mail object 36 | mail = mt.Mail( 37 | sender=mt.Address(email="mailtrap@example.com", name="Mailtrap Test"), 38 | to=[mt.Address(email="your@email.com")], 39 | subject="You are awesome!", 40 | text="Congrats for sending test email with Mailtrap!", 41 | ) 42 | 43 | # create client and send 44 | client = mt.MailtrapClient(token="your-api-key") 45 | client.send(mail) 46 | ``` 47 | 48 | ### Full 49 | 50 | ```python 51 | import base64 52 | from pathlib import Path 53 | 54 | import mailtrap as mt 55 | 56 | welcome_image = Path(__file__).parent.joinpath("welcome.png").read_bytes() 57 | 58 | mail = mt.Mail( 59 | sender=mt.Address(email="mailtrap@example.com", name="Mailtrap Test"), 60 | to=[mt.Address(email="your@email.com", name="Your name")], 61 | cc=[mt.Address(email="cc@email.com", name="Copy to")], 62 | bcc=[mt.Address(email="bcc@email.com", name="Hidden Recipient")], 63 | subject="You are awesome!", 64 | text="Congrats for sending test email with Mailtrap!", 65 | html=""" 66 | 67 | 68 | 69 | 70 | 71 | 72 |
73 |

74 | Congrats for sending test email with Mailtrap! 75 |

76 |

Inspect it using the tabs you see above and learn how this email can be improved.

77 | Inspect with Tabs 78 |

Now send your email using our fake SMTP server and integration of your choice!

79 |

Good luck! Hope it works.

80 |
81 | 82 | 86 | 87 | 88 | """, 89 | category="Test", 90 | attachments=[ 91 | mt.Attachment( 92 | content=base64.b64encode(welcome_image), 93 | filename="welcome.png", 94 | disposition=mt.Disposition.INLINE, 95 | mimetype="image/png", 96 | content_id="welcome.png", 97 | ) 98 | ], 99 | headers={"X-MT-Header": "Custom header"}, 100 | custom_variables={"year": 2023}, 101 | ) 102 | 103 | client = mt.MailtrapClient(token="your-api-key") 104 | client.send(mail) 105 | ``` 106 | 107 | ### Using email template 108 | 109 | ```python 110 | import mailtrap as mt 111 | 112 | # create mail object 113 | mail = mt.MailFromTemplate( 114 | sender=mt.Address(email="mailtrap@example.com", name="Mailtrap Test"), 115 | to=[mt.Address(email="your@email.com")], 116 | template_uuid="2f45b0aa-bbed-432f-95e4-e145e1965ba2", 117 | template_variables={"user_name": "John Doe"}, 118 | ) 119 | 120 | # create client and send 121 | client = mt.MailtrapClient(token="your-api-key") 122 | client.send(mail) 123 | ``` 124 | 125 | ## Contributing 126 | 127 | Bug reports and pull requests are welcome on [GitHub](https://github.com/railsware/mailtrap-python). This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](CODE_OF_CONDUCT.md). 128 | 129 | ### Development Environment 130 | 131 | #### Clone the repo 132 | 133 | ```bash 134 | https://github.com/railsware/mailtrap-python.git 135 | cd mailtrap-python 136 | ``` 137 | 138 | #### Install [tox](https://tox.wiki/en/latest/installation.html) 139 | 140 | `tox` is an environment orchestrator. We use it to setup local environments, run tests and execute linters. 141 | 142 | ```bash 143 | python -m pip install --user tox 144 | python -m tox --help 145 | ``` 146 | 147 | To setup virtual environments, run tests and linters use: 148 | 149 | ```bash 150 | tox 151 | ``` 152 | 153 | It will create virtual environments with all installed dependencies for each available python interpreter (starting from `python3.6`) on your machine. 154 | By default, they will be available in `{project}/.tox/` directory. So, for instance, to activate `python3.11` environment, run the following: 155 | 156 | ```bash 157 | source .tox/py311/bin/activate 158 | ``` 159 | 160 | ## Information for version 1 users 161 | 162 | If you are a version 1 user, it is advised that you upgrade to [Sendria](https://github.com/msztolcman/sendria), which is the same package, but under a new name, and with [new features](https://github.com/msztolcman/sendria#changelog). However, you can also continue using the last v1 release by locking the version in pip: 163 | 164 | ```sh 165 | # To use the FORMER version of the mailtrap package, now known as Sendria: 166 | pip install --force-reinstall -v "mailtrap==1.0.1" 167 | ``` 168 | 169 | ## License 170 | 171 | The project is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT). 172 | 173 | ## Code of Conduct 174 | 175 | Everyone interacting in the Mailtrap project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](CODE_OF_CONDUCT.md) 176 | -------------------------------------------------------------------------------- /mailtrap/__init__.py: -------------------------------------------------------------------------------- 1 | from .client import MailtrapClient 2 | from .exceptions import APIError 3 | from .exceptions import AuthorizationError 4 | from .exceptions import ClientConfigurationError 5 | from .exceptions import MailtrapError 6 | from .mail import Address 7 | from .mail import Attachment 8 | from .mail import BaseEntity 9 | from .mail import BaseMail 10 | from .mail import Disposition 11 | from .mail import Mail 12 | from .mail import MailFromTemplate 13 | -------------------------------------------------------------------------------- /mailtrap/client.py: -------------------------------------------------------------------------------- 1 | from typing import NoReturn 2 | from typing import Optional 3 | from typing import Union 4 | 5 | import requests 6 | 7 | from mailtrap.exceptions import APIError 8 | from mailtrap.exceptions import AuthorizationError 9 | from mailtrap.exceptions import ClientConfigurationError 10 | from mailtrap.mail.base import BaseMail 11 | 12 | 13 | class MailtrapClient: 14 | DEFAULT_HOST = "send.api.mailtrap.io" 15 | DEFAULT_PORT = 443 16 | BULK_HOST = "bulk.api.mailtrap.io" 17 | SANDBOX_HOST = "sandbox.api.mailtrap.io" 18 | 19 | def __init__( 20 | self, 21 | token: str, 22 | api_host: Optional[str] = None, 23 | api_port: int = DEFAULT_PORT, 24 | bulk: bool = False, 25 | sandbox: bool = False, 26 | inbox_id: Optional[str] = None, 27 | ) -> None: 28 | self.token = token 29 | self.api_host = api_host 30 | self.api_port = api_port 31 | self.bulk = bulk 32 | self.sandbox = sandbox 33 | self.inbox_id = inbox_id 34 | 35 | self._validate_itself() 36 | 37 | def send(self, mail: BaseMail) -> dict[str, Union[bool, list[str]]]: 38 | response = requests.post( 39 | self.api_send_url, headers=self.headers, json=mail.api_data 40 | ) 41 | 42 | if response.ok: 43 | data: dict[str, Union[bool, list[str]]] = response.json() 44 | return data 45 | 46 | self._handle_failed_response(response) 47 | 48 | @property 49 | def base_url(self) -> str: 50 | return f"https://{self._host.rstrip('/')}:{self.api_port}" 51 | 52 | @property 53 | def api_send_url(self) -> str: 54 | url = f"{self.base_url}/api/send" 55 | if self.sandbox and self.inbox_id: 56 | return f"{url}/{self.inbox_id}" 57 | 58 | return url 59 | 60 | @property 61 | def headers(self) -> dict[str, str]: 62 | return { 63 | "Authorization": f"Bearer {self.token}", 64 | "Content-Type": "application/json", 65 | "User-Agent": ( 66 | "mailtrap-python (https://github.com/railsware/mailtrap-python)" 67 | ), 68 | } 69 | 70 | @property 71 | def _host(self) -> str: 72 | if self.api_host: 73 | return self.api_host 74 | if self.sandbox: 75 | return self.SANDBOX_HOST 76 | if self.bulk: 77 | return self.BULK_HOST 78 | return self.DEFAULT_HOST 79 | 80 | @staticmethod 81 | def _handle_failed_response(response: requests.Response) -> NoReturn: 82 | status_code = response.status_code 83 | data = response.json() 84 | 85 | if status_code == 401: 86 | raise AuthorizationError(data["errors"]) 87 | 88 | raise APIError(status_code, data["errors"]) 89 | 90 | def _validate_itself(self) -> None: 91 | if self.sandbox and not self.inbox_id: 92 | raise ClientConfigurationError("`inbox_id` is required for sandbox mode") 93 | 94 | if not self.sandbox and self.inbox_id: 95 | raise ClientConfigurationError( 96 | "`inbox_id` is not allowed in non-sandbox mode" 97 | ) 98 | 99 | if self.bulk and self.sandbox: 100 | raise ClientConfigurationError("bulk mode is not allowed in sandbox mode") 101 | -------------------------------------------------------------------------------- /mailtrap/exceptions.py: -------------------------------------------------------------------------------- 1 | class MailtrapError(Exception): 2 | pass 3 | 4 | 5 | class ClientConfigurationError(MailtrapError): 6 | def __init__(self, message: str) -> None: 7 | super().__init__(message) 8 | 9 | 10 | class APIError(MailtrapError): 11 | def __init__(self, status: int, errors: list[str]) -> None: 12 | self.status = status 13 | self.errors = errors 14 | 15 | super().__init__("; ".join(errors)) 16 | 17 | 18 | class AuthorizationError(APIError): 19 | def __init__(self, errors: list[str]) -> None: 20 | super().__init__(status=401, errors=errors) 21 | -------------------------------------------------------------------------------- /mailtrap/mail/__init__.py: -------------------------------------------------------------------------------- 1 | from .address import Address 2 | from .attachment import Attachment 3 | from .attachment import Disposition 4 | from .base import BaseMail 5 | from .base_entity import BaseEntity 6 | from .from_template import MailFromTemplate 7 | from .mail import Mail 8 | -------------------------------------------------------------------------------- /mailtrap/mail/address.py: -------------------------------------------------------------------------------- 1 | from typing import Any 2 | from typing import Optional 3 | 4 | from mailtrap.mail.base_entity import BaseEntity 5 | 6 | 7 | class Address(BaseEntity): 8 | def __init__(self, email: str, name: Optional[str] = None) -> None: 9 | self.email = email 10 | self.name = name 11 | 12 | @property 13 | def api_data(self) -> dict[str, Any]: 14 | return self.omit_none_values({"email": self.email, "name": self.name}) 15 | -------------------------------------------------------------------------------- /mailtrap/mail/attachment.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | from typing import Any 3 | from typing import Optional 4 | 5 | from mailtrap.mail.base_entity import BaseEntity 6 | 7 | 8 | class Disposition(Enum): 9 | INLINE = "inline" 10 | ATTACHMENT = "attachment" 11 | 12 | 13 | class Attachment(BaseEntity): 14 | def __init__( 15 | self, 16 | content: bytes, 17 | filename: str, 18 | disposition: Optional[Disposition] = None, 19 | mimetype: Optional[str] = None, 20 | content_id: Optional[str] = None, 21 | ) -> None: 22 | self.content = content 23 | self.filename = filename 24 | self.mimetype = mimetype 25 | self.disposition = disposition 26 | self.content_id = content_id 27 | 28 | @property 29 | def api_data(self) -> dict[str, Any]: 30 | return self.omit_none_values( 31 | { 32 | "content": self.content.decode(), 33 | "filename": self.filename, 34 | "type": self.mimetype, 35 | "disposition": self.disposition.value if self.disposition else None, 36 | "content_id": self.content_id, 37 | } 38 | ) 39 | -------------------------------------------------------------------------------- /mailtrap/mail/base.py: -------------------------------------------------------------------------------- 1 | from abc import ABCMeta 2 | from collections.abc import Sequence 3 | from typing import Any 4 | from typing import Optional 5 | 6 | from mailtrap.mail.address import Address 7 | from mailtrap.mail.attachment import Attachment 8 | from mailtrap.mail.base_entity import BaseEntity 9 | 10 | 11 | class BaseMail(BaseEntity, metaclass=ABCMeta): 12 | """Base abstract class for mails.""" 13 | 14 | def __init__( 15 | self, 16 | sender: Address, 17 | to: list[Address], 18 | cc: Optional[list[Address]] = None, 19 | bcc: Optional[list[Address]] = None, 20 | attachments: Optional[list[Attachment]] = None, 21 | headers: Optional[dict[str, str]] = None, 22 | custom_variables: Optional[dict[str, Any]] = None, 23 | ) -> None: 24 | self.sender = sender 25 | self.to = to 26 | self.cc = cc 27 | self.bcc = bcc 28 | self.attachments = attachments 29 | self.headers = headers 30 | self.custom_variables = custom_variables 31 | 32 | @property 33 | def api_data(self) -> dict[str, Any]: 34 | return self.omit_none_values( 35 | { 36 | "from": self.sender.api_data, 37 | "to": self.get_api_data_from_list(self.to), 38 | "cc": self.get_api_data_from_list(self.cc), 39 | "bcc": self.get_api_data_from_list(self.bcc), 40 | "attachments": self.get_api_data_from_list(self.attachments), 41 | "headers": self.headers, 42 | "custom_variables": self.custom_variables, 43 | } 44 | ) 45 | 46 | @staticmethod 47 | def get_api_data_from_list( 48 | items: Optional[Sequence[BaseEntity]], 49 | ) -> Optional[list[dict[str, Any]]]: 50 | if items is None: 51 | return None 52 | 53 | return [item.api_data for item in items] 54 | -------------------------------------------------------------------------------- /mailtrap/mail/base_entity.py: -------------------------------------------------------------------------------- 1 | from abc import ABCMeta 2 | from abc import abstractmethod 3 | from typing import Any 4 | 5 | 6 | class BaseEntity(metaclass=ABCMeta): 7 | @property 8 | @abstractmethod 9 | def api_data(self) -> dict[str, Any]: 10 | raise NotImplementedError 11 | 12 | @staticmethod 13 | def omit_none_values(data: dict[str, Any]) -> dict[str, Any]: 14 | return {key: value for key, value in data.items() if value is not None} 15 | -------------------------------------------------------------------------------- /mailtrap/mail/from_template.py: -------------------------------------------------------------------------------- 1 | from typing import Any 2 | from typing import Optional 3 | 4 | from mailtrap.mail.address import Address 5 | from mailtrap.mail.attachment import Attachment 6 | from mailtrap.mail.base import BaseMail 7 | 8 | 9 | class MailFromTemplate(BaseMail): 10 | """Creates `EmailFromTemplate` request body for /api/send Mailtrap API v2 11 | endpoint.""" 12 | 13 | def __init__( 14 | self, 15 | sender: Address, 16 | to: list[Address], 17 | template_uuid: str, 18 | template_variables: Optional[dict[str, Any]] = None, 19 | cc: Optional[list[Address]] = None, 20 | bcc: Optional[list[Address]] = None, 21 | attachments: Optional[list[Attachment]] = None, 22 | headers: Optional[dict[str, str]] = None, 23 | custom_variables: Optional[dict[str, Any]] = None, 24 | ) -> None: 25 | super().__init__( 26 | sender=sender, 27 | to=to, 28 | cc=cc, 29 | bcc=bcc, 30 | attachments=attachments, 31 | headers=headers, 32 | custom_variables=custom_variables, 33 | ) 34 | self.template_uuid = template_uuid 35 | self.template_variables = template_variables 36 | 37 | @property 38 | def api_data(self) -> dict[str, Any]: 39 | return self.omit_none_values( 40 | { 41 | **super().api_data, 42 | "template_uuid": self.template_uuid, 43 | "template_variables": self.template_variables, 44 | } 45 | ) 46 | -------------------------------------------------------------------------------- /mailtrap/mail/mail.py: -------------------------------------------------------------------------------- 1 | from typing import Any 2 | from typing import Optional 3 | 4 | from mailtrap.mail.address import Address 5 | from mailtrap.mail.attachment import Attachment 6 | from mailtrap.mail.base import BaseMail 7 | 8 | 9 | class Mail(BaseMail): 10 | """Creates a request body for /api/send Mailtrap API v2 endpoint. 11 | 12 | Either `text` or `html` param must be specified. You can also 13 | provide both of them. 14 | 15 | If only `text` is provided, `EmailWithText` body type will be used. 16 | If only `html` is provided, `HtmlWithText` body type will be used. 17 | If both `text` and `html` are provided, 18 | `EmailWithTextAndHtml` body type will be used. 19 | """ 20 | 21 | def __init__( 22 | self, 23 | sender: Address, 24 | to: list[Address], 25 | subject: str, 26 | text: Optional[str] = None, 27 | html: Optional[str] = None, 28 | category: Optional[str] = None, 29 | cc: Optional[list[Address]] = None, 30 | bcc: Optional[list[Address]] = None, 31 | attachments: Optional[list[Attachment]] = None, 32 | headers: Optional[dict[str, str]] = None, 33 | custom_variables: Optional[dict[str, Any]] = None, 34 | ) -> None: 35 | super().__init__( 36 | sender=sender, 37 | to=to, 38 | cc=cc, 39 | bcc=bcc, 40 | attachments=attachments, 41 | headers=headers, 42 | custom_variables=custom_variables, 43 | ) 44 | self.subject = subject 45 | self.text = text 46 | self.html = html 47 | self.category = category 48 | 49 | @property 50 | def api_data(self) -> dict[str, Any]: 51 | return self.omit_none_values( 52 | { 53 | **super().api_data, 54 | "subject": self.subject, 55 | "text": self.text, 56 | "html": self.html, 57 | "category": self.category, 58 | } 59 | ) 60 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "mailtrap" 3 | version = "2.1.0" 4 | description = "Official mailtrap.io API client" 5 | readme = "README.md" 6 | license = {file = "LICENSE.txt"} 7 | authors = [{name = "Railsware Products Studio LLC", email = "support@mailtrap.io"}] 8 | classifiers = [ 9 | "License :: OSI Approved :: MIT License", 10 | "Operating System :: OS Independent", 11 | "Topic :: Software Development :: Libraries :: Application Frameworks", 12 | "Programming Language :: Python :: 3", 13 | "Programming Language :: Python :: 3.9", 14 | "Programming Language :: Python :: 3.10", 15 | "Programming Language :: Python :: 3.11", 16 | "Programming Language :: Python :: 3.12", 17 | "Programming Language :: Python :: 3.13", 18 | ] 19 | requires-python = ">=3.9" 20 | dependencies = [ 21 | "requests>=2.26.0", 22 | ] 23 | 24 | [project.urls] 25 | Homepage = "https://mailtrap.io/" 26 | Documentation = "https://github.com/railsware/mailtrap-python" 27 | Repository = "https://github.com/railsware/mailtrap-python.git" 28 | "API documentation" = "https://api-docs.mailtrap.io/" 29 | 30 | [build-system] 31 | requires = ["setuptools"] 32 | build-backend = "setuptools.build_meta" 33 | 34 | [tool.isort] 35 | profile = "black" 36 | line_length = 90 37 | force_single_line = true 38 | 39 | [tool.black] 40 | line-length = 90 41 | 42 | [tool.mypy] 43 | strict = true 44 | check_untyped_defs = true 45 | ignore_missing_imports = true 46 | implicit_reexport = true 47 | -------------------------------------------------------------------------------- /requirements.test.txt: -------------------------------------------------------------------------------- 1 | pytest>=7.0.1 2 | responses>=0.17.0 3 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests>=2.26.0 2 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/railsware/mailtrap-python/709f09625ccdf3d192bb465550ddfda59541d3e2/tests/__init__.py -------------------------------------------------------------------------------- /tests/unit/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/railsware/mailtrap-python/709f09625ccdf3d192bb465550ddfda59541d3e2/tests/unit/__init__.py -------------------------------------------------------------------------------- /tests/unit/mail/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/railsware/mailtrap-python/709f09625ccdf3d192bb465550ddfda59541d3e2/tests/unit/mail/__init__.py -------------------------------------------------------------------------------- /tests/unit/mail/test_address.py: -------------------------------------------------------------------------------- 1 | from mailtrap.mail.address import Address 2 | 3 | 4 | class TestAddress: 5 | def test_api_data_should_return_dict_with_required_props_only(self) -> None: 6 | entity = Address(email="joe@mail.com") 7 | assert entity.api_data == {"email": "joe@mail.com"} 8 | 9 | def test_api_data_should_return_dict_with_all_props(self) -> None: 10 | entity = Address(email="joe@mail.com", name="Joe") 11 | assert entity.api_data == {"email": "joe@mail.com", "name": "Joe"} 12 | -------------------------------------------------------------------------------- /tests/unit/mail/test_attachment.py: -------------------------------------------------------------------------------- 1 | from mailtrap.mail.attachment import Attachment 2 | from mailtrap.mail.attachment import Disposition 3 | 4 | 5 | class TestAttachment: 6 | def test_api_data_should_return_dict_with_required_props_only(self) -> None: 7 | entity = Attachment(content=b"base64_content", filename="photo.jpg") 8 | assert entity.api_data == {"content": "base64_content", "filename": "photo.jpg"} 9 | 10 | def test_api_data_should_return_dict_with_all_props(self) -> None: 11 | entity = Attachment( 12 | content=b"base64_content", 13 | filename="photo.jpg", 14 | disposition=Disposition.INLINE, 15 | mimetype="image/jpg", 16 | content_id="test_id", 17 | ) 18 | assert entity.api_data == { 19 | "content": "base64_content", 20 | "filename": "photo.jpg", 21 | "type": "image/jpg", 22 | "disposition": "inline", 23 | "content_id": "test_id", 24 | } 25 | -------------------------------------------------------------------------------- /tests/unit/mail/test_from_template.py: -------------------------------------------------------------------------------- 1 | from mailtrap.mail.from_template import MailFromTemplate 2 | from mailtrap.mail.mail import Address 3 | from mailtrap.mail.mail import Attachment 4 | 5 | 6 | class TestAttachment: 7 | ADDRESS = Address(email="joe@mail.com") 8 | ADDRESS_API_DATA = {"email": "joe@mail.com"} 9 | 10 | ATTACHMENT = Attachment(content=b"base64_content", filename="file.txt") 11 | ATTACHMENT_API_DATA = {"content": "base64_content", "filename": "file.txt"} 12 | 13 | def test_api_data_should_return_dict_with_required_props_only(self) -> None: 14 | entity = MailFromTemplate( 15 | sender=self.ADDRESS, 16 | to=[self.ADDRESS], 17 | template_uuid="fake_uuid", 18 | ) 19 | assert entity.api_data == { 20 | "from": self.ADDRESS_API_DATA, 21 | "to": [self.ADDRESS_API_DATA], 22 | "template_uuid": "fake_uuid", 23 | } 24 | 25 | def test_api_data_should_return_dict_with_all_props(self) -> None: 26 | entity = MailFromTemplate( 27 | sender=self.ADDRESS, 28 | to=[self.ADDRESS], 29 | template_uuid="fake_uuid", 30 | template_variables={"username": "Joe"}, 31 | cc=[self.ADDRESS], 32 | bcc=[self.ADDRESS], 33 | attachments=[self.ATTACHMENT], 34 | headers={"key": "value"}, 35 | custom_variables={"var": 42}, 36 | ) 37 | 38 | assert entity.api_data == { 39 | "from": self.ADDRESS_API_DATA, 40 | "to": [self.ADDRESS_API_DATA], 41 | "template_uuid": "fake_uuid", 42 | "template_variables": {"username": "Joe"}, 43 | "cc": [self.ADDRESS_API_DATA], 44 | "bcc": [self.ADDRESS_API_DATA], 45 | "attachments": [self.ATTACHMENT_API_DATA], 46 | "headers": {"key": "value"}, 47 | "custom_variables": {"var": 42}, 48 | } 49 | -------------------------------------------------------------------------------- /tests/unit/mail/test_mail.py: -------------------------------------------------------------------------------- 1 | from mailtrap.mail.mail import Address 2 | from mailtrap.mail.mail import Attachment 3 | from mailtrap.mail.mail import Mail 4 | 5 | 6 | class TestAttachment: 7 | ADDRESS = Address(email="joe@mail.com") 8 | ADDRESS_API_DATA = {"email": "joe@mail.com"} 9 | 10 | ATTACHMENT = Attachment(content=b"base64_content", filename="file.txt") 11 | ATTACHMENT_API_DATA = {"content": "base64_content", "filename": "file.txt"} 12 | 13 | def test_api_data_should_return_dict_with_required_props_only(self) -> None: 14 | entity = Mail( 15 | sender=self.ADDRESS, 16 | to=[self.ADDRESS], 17 | subject="Email subject", 18 | text="email text", 19 | ) 20 | assert entity.api_data == { 21 | "from": self.ADDRESS_API_DATA, 22 | "to": [self.ADDRESS_API_DATA], 23 | "subject": "Email subject", 24 | "text": "email text", 25 | } 26 | 27 | def test_api_data_should_return_dict_with_all_props(self) -> None: 28 | entity = Mail( 29 | sender=self.ADDRESS, 30 | to=[self.ADDRESS], 31 | subject="Email subject", 32 | text="email text", 33 | html="email html", 34 | cc=[self.ADDRESS], 35 | bcc=[self.ADDRESS], 36 | attachments=[self.ATTACHMENT], 37 | headers={"key": "value"}, 38 | custom_variables={"var": 42}, 39 | category="test_category", 40 | ) 41 | 42 | assert entity.api_data == { 43 | "from": self.ADDRESS_API_DATA, 44 | "to": [self.ADDRESS_API_DATA], 45 | "subject": "Email subject", 46 | "text": "email text", 47 | "html": "email html", 48 | "cc": [self.ADDRESS_API_DATA], 49 | "bcc": [self.ADDRESS_API_DATA], 50 | "attachments": [self.ATTACHMENT_API_DATA], 51 | "headers": {"key": "value"}, 52 | "custom_variables": {"var": 42}, 53 | "category": "test_category", 54 | } 55 | -------------------------------------------------------------------------------- /tests/unit/test_client.py: -------------------------------------------------------------------------------- 1 | import json 2 | from typing import Any 3 | 4 | import pytest 5 | import responses 6 | 7 | import mailtrap as mt 8 | 9 | DUMMY_ADDRESS = mt.Address(email="joe@mail.com") 10 | DUMMY_MAIL = mt.Mail( 11 | sender=DUMMY_ADDRESS, 12 | to=[DUMMY_ADDRESS], 13 | subject="Email subject", 14 | text="email text", 15 | ) 16 | DUMMY_MAIL_FROM_TEMPLATE = mt.MailFromTemplate( 17 | sender=DUMMY_ADDRESS, 18 | to=[DUMMY_ADDRESS], 19 | template_uuid="fake_uuid", 20 | ) 21 | 22 | MAIL_ENTITIES = [DUMMY_MAIL, DUMMY_MAIL_FROM_TEMPLATE] 23 | 24 | 25 | class TestMailtrapClient: 26 | SEND_URL = "https://send.api.mailtrap.io:443/api/send" 27 | 28 | @staticmethod 29 | def get_client(**kwargs: Any) -> mt.MailtrapClient: 30 | props = {"token": "fake_token", **kwargs} 31 | return mt.MailtrapClient(**props) 32 | 33 | @pytest.mark.parametrize( 34 | "arguments", 35 | [ 36 | {"sandbox": True}, 37 | {"inbox_id": "12345"}, 38 | {"bulk": True, "sandbox": True, "inbox_id": "12345"}, 39 | ], 40 | ) 41 | def test_client_validation(self, arguments: dict[str, Any]) -> None: 42 | with pytest.raises(mt.ClientConfigurationError): 43 | self.get_client(**arguments) 44 | 45 | def test_base_url_should_truncate_slash_from_host(self) -> None: 46 | client = self.get_client(api_host="example.send.com/", api_port=543) 47 | 48 | assert client.base_url == "https://example.send.com:543" 49 | 50 | @pytest.mark.parametrize( 51 | "arguments, expected_url", 52 | [ 53 | ({}, "https://send.api.mailtrap.io:443/api/send"), 54 | ( 55 | {"api_host": "example.send.com", "api_port": 543}, 56 | "https://example.send.com:543/api/send", 57 | ), 58 | ( 59 | {"api_host": "example.send.com", "sandbox": True, "inbox_id": "12345"}, 60 | "https://example.send.com:443/api/send/12345", 61 | ), 62 | ( 63 | {"api_host": "example.send.com", "bulk": True}, 64 | "https://example.send.com:443/api/send", 65 | ), 66 | ( 67 | {"sandbox": True, "inbox_id": "12345"}, 68 | "https://sandbox.api.mailtrap.io:443/api/send/12345", 69 | ), 70 | ( 71 | {"bulk": True}, 72 | "https://bulk.api.mailtrap.io:443/api/send", 73 | ), 74 | ], 75 | ) 76 | def test_api_send_url_should_return_default_sending_url( 77 | self, arguments: dict[str, Any], expected_url: str 78 | ) -> None: 79 | client = self.get_client(**arguments) 80 | 81 | assert client.api_send_url == expected_url 82 | 83 | def test_headers_should_return_appropriate_dict(self) -> None: 84 | client = self.get_client() 85 | 86 | assert client.headers == { 87 | "Authorization": "Bearer fake_token", 88 | "Content-Type": "application/json", 89 | "User-Agent": ( 90 | "mailtrap-python (https://github.com/railsware/mailtrap-python)" 91 | ), 92 | } 93 | 94 | @responses.activate 95 | @pytest.mark.parametrize("mail", MAIL_ENTITIES) 96 | def test_send_should_handle_success_response(self, mail: mt.BaseMail) -> None: 97 | response_body = {"success": True, "message_ids": ["12345"]} 98 | responses.add(responses.POST, self.SEND_URL, json=response_body) 99 | 100 | client = self.get_client() 101 | result = client.send(mail) 102 | 103 | assert result == response_body 104 | assert len(responses.calls) == 1 105 | request = responses.calls[0].request # type: ignore 106 | assert request.headers.items() >= client.headers.items() 107 | assert request.body == json.dumps(mail.api_data).encode() 108 | 109 | @responses.activate 110 | @pytest.mark.parametrize("mail", MAIL_ENTITIES) 111 | def test_send_should_raise_authorization_error(self, mail: mt.BaseMail) -> None: 112 | response_body = {"errors": ["Unauthorized"]} 113 | responses.add(responses.POST, self.SEND_URL, json=response_body, status=401) 114 | 115 | client = self.get_client() 116 | 117 | with pytest.raises(mt.AuthorizationError): 118 | client.send(mail) 119 | 120 | @responses.activate 121 | @pytest.mark.parametrize("mail", MAIL_ENTITIES) 122 | def test_send_should_raise_api_error_for_400_status_code( 123 | self, mail: mt.BaseMail 124 | ) -> None: 125 | response_body = {"errors": ["Some error msg"]} 126 | responses.add(responses.POST, self.SEND_URL, json=response_body, status=400) 127 | 128 | client = self.get_client() 129 | 130 | with pytest.raises(mt.APIError): 131 | client.send(mail) 132 | 133 | @responses.activate 134 | @pytest.mark.parametrize("mail", MAIL_ENTITIES) 135 | def test_send_should_raise_api_error_for_500_status_code( 136 | self, mail: mt.BaseMail 137 | ) -> None: 138 | response_body = {"errors": ["Some error msg"]} 139 | responses.add(responses.POST, self.SEND_URL, json=response_body, status=500) 140 | 141 | client = self.get_client() 142 | 143 | with pytest.raises(mt.APIError): 144 | client.send(mail) 145 | -------------------------------------------------------------------------------- /tests/unit/test_exceptions.py: -------------------------------------------------------------------------------- 1 | from mailtrap.exceptions import APIError 2 | from mailtrap.exceptions import AuthorizationError 3 | 4 | 5 | class TestAPIError: 6 | def test_str_representation_single_error_message(self) -> None: 7 | error = APIError(status=400, errors=["Error msg"]) 8 | 9 | assert str(error) == "Error msg" 10 | 11 | def test_str_representation_multiple_error_messages(self) -> None: 12 | error = APIError(status=400, errors=["Error msg 1", "Error msg 2"]) 13 | 14 | assert str(error) == "Error msg 1; Error msg 2" 15 | 16 | 17 | class TestAuthorizationError: 18 | def test_str_representation_single_error_message(self) -> None: 19 | error = AuthorizationError(errors=["Error msg"]) 20 | 21 | assert str(error) == "Error msg" 22 | 23 | def test_str_representation(self) -> None: 24 | error = AuthorizationError(errors=["Error msg 1", "Error msg 2"]) 25 | 26 | assert str(error) == "Error msg 1; Error msg 2" 27 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | isolated_build = true 3 | envlist = 4 | py{39,310,311,312,313}, 5 | pre-commit 6 | mypy 7 | skip_missing_interpreters = true 8 | 9 | [testenv] 10 | description = run unit tests 11 | deps = 12 | -r requirements.txt 13 | -r requirements.test.txt 14 | commands = 15 | pytest -q {posargs} 16 | 17 | [testenv:pre-commit] 18 | deps = pre-commit==4.2.0 19 | commands = pre-commit run --all-files 20 | 21 | [testenv:mypy] 22 | deps = 23 | -r requirements.test.txt 24 | mypy==1.15.0 25 | types-requests 26 | commands = mypy ./mailtrap 27 | 28 | [testenv:build] 29 | deps = build 30 | commands = 31 | python -m build 32 | 33 | [testenv:publish] 34 | deps = twine 35 | commands = 36 | python -m twine upload dist/* 37 | --------------------------------------------------------------------------------