Skip to content

Commit

Permalink
Initialize MailTmWrapper package and add GitHub Actions workflow for …
Browse files Browse the repository at this point in the history
…publishing
  • Loading branch information
sexfrance committed Dec 11, 2024
0 parents commit 96b1f62
Show file tree
Hide file tree
Showing 7 changed files with 415 additions and 0 deletions.
35 changes: 35 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
name: Publish Python Package

on:
push:
branches:
- main

jobs:
publish:
runs-on: ubuntu-latest

steps:
- name: Checkout the code
uses: actions/checkout@v3

- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.x"

- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install setuptools wheel twine
- name: Build the package
run: |
python setup.py sdist bdist_wheel
- name: Publish to PyPI
env:
TWINE_USERNAME: "__token__"
TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }}
run: |
python -m twine upload dist/*
45 changes: 45 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# Distribution / packaging
build/
dist/
*.egg-info/

# PyInstaller
# Usually these files are written by a python script from a template
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Virtual environment
venv/
env/
ENV/
.venv/
.ENV/

# Jupyter Notebook
.ipynb_checkpoints/

# VS Code files (if using VSCode)
.vscode/

# PyCharm files
.idea/

# Mac OS files
.DS_Store

# Backup files
*.bak
*.swp

# Log
.log
logs/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) Sexfrance 2024

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
200 changes: 200 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
# MailTM Wrapper

**MailTmWrapper** is a Python library designed to interact with the Mail.TM API, providing an easy-to-use interface for creating temporary email accounts and managing email messages programmatically. This wrapper simplifies operations such as generating tokens, retrieving messages, and managing accounts.

## 🔥 Features

- Create and manage temporary email accounts.
- Generate tokens for authenticated API requests.
- Fetch, read, and delete email messages.
- Retrieve domains and account information.
- Minimal dependencies and easy integration.
- Supports custom proxy configurations for network flexibility.

## ⚙️ Installation

To install the package locally, clone the repository and run:

```bash
pip install .
```

You can also install it via `pip` from PyPI:

```bash
pip install logmagix
```

## 🔧 Usage

### Importing the Package

```python
from mailtmwrapper import MailTM
```

### Creating an Account

You can create a temporary email account using the `create_account` method:

```python
mail = MailTM()

# Create a new temporary email account
account = mail.create_account()
email = account['address']
password = account['password']
print(f"Temporary email: {email}")
```

If you prefer, you can specify a custom email address and password:

```python
account = mail.create_account(email="custom_address@domain.com", password="CustomPassword123?")
```

### Generating a Token

To perform authenticated operations, generate a token using the `create_token` method:

```python
token = mail.create_token(email, password)
print(f"Generated token: {token}")
```

### Fetching Emails

Retrieve the list of email messages associated with your account:

```python
messages = mail.get_messages()
print("Messages:", messages)
```

You can also fetch specific message details by ID:

```python
message_id = messages['hydra:member'][0]['id']
message_details = mail.get_message_by_id(message_id)
print("Message details:", message_details)
```

### Deleting Emails

Delete an email message by its ID:

```python
message_id = "your_message_id"
success, status_code = mail.delete_message(message_id)
if success:
print("Message deleted successfully.")
else:
print(f"Failed to delete message. Status code: {status_code}")
```

### Managing Accounts

#### Retrieve Account Information

Get account details using the `get_me` method:

```python
account_info = mail.get_me()
print("Account info:", account_info)
```

#### Delete an Account

Delete the temporary email account:

```python
success, status_code = mail.delete_account(account_id="your_account_id")
if success:
print("Account deleted successfully.")
else:
print(f"Failed to delete account. Status code: {status_code}")
```

### Working with Domains

#### Retrieve Available Domains

Fetch the list of domains supported by Mail.TM:

```python
domains = mail.get_domains()
print("Domains:", domains)
```

#### Fetch Domain Details

Get details of a specific domain by its ID:

```python
domain_id = "your_domain_id"
domain_details = mail.get_domain_by_id(domain_id)
print("Domain details:", domain_details)
```

## Full Example

Here is a full example combining account creation, token generation, and email fetching:

```python
from mailtm_wrapper import MailTM

mail = MailTM()

# Create a temporary account
account = mail.create_account()
email = account['address']
password = account['password']
print(f"Temporary email: {email}")

# Generate a token
token = mail.create_token(email, password)
print(f"Generated token: {token}")

# Fetch messages
messages = mail.get_messages()
print("Messages:", messages)

# Retrieve message details
if messages['hydra:member']:
message_id = messages['hydra:member'][0]['id']
message_details = mail.get_message_by_id(message_id)
print("Message details:", message_details)

# Delete the account
success, status_code = mail.delete_account(account_id=account['id'])
if success:
print("Account deleted successfully.")
else:
print(f"Failed to delete account. Status code: {status_code}")
```


## ❗ Requirements

MailTmWrapper requires:

- `requests` to send requests to the Mail.TM API.
To install dependencies manually, run:

```bash
pip install requests
```

## ©️ License

MailTmWrapper is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details.
[Mail.TM](https://mail.tm/).

## 🖥️ Contributing

Contributions are welcome! Feel free to fork the repository, make changes, and submit a pull request.

## 👤 Author

MailTmWrapper is developed and maintained by **sexfrance**.
[Mail.TM](https://mail.tm/) is developed and maintained by **MailTM**.
88 changes: 88 additions & 0 deletions mailtmwrapper/MailTmWrapper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import requests
import random
import string
from typing import Tuple, Dict, Union

class MailTM:
BASE_URL = "https://api.mail.tm"

def __init__(self, token: str = None, proxy_dict: Dict = None):
self.token = token
self.proxy_dict = proxy_dict
self.headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
if token:
self.headers['Authorization'] = f'Bearer {token}'

def _make_request(self, method: str, endpoint: str, data: Dict = None) -> Union[Dict, int]:
url = f"{self.BASE_URL}/{endpoint}"
response = requests.request(
method=method,
url=url,
json=data,
headers=self.headers,
proxies=self.proxy_dict
)

if response.status_code in [200, 201]:
return response.json()
elif response.status_code == 204:
return response.status_code
return response.status_code

def create_account(self, email: str = None, password: str = None) -> Dict:
if not email:
email = f"temp_{random.randint(1, 999999999)}@freesourcecodes.com"
if not password:
password = ''.join(random.choices(string.ascii_letters + string.digits + "!@#$%^&*()_+-=[]{}|;:,.<>?/", k=16))

return self._make_request('POST', 'accounts', {'address': email, 'password': password})

def create_token(self, email: str, password: str) -> str:
response = self._make_request('POST', 'token', {'address': email, 'password': password})
if isinstance(response, dict):
self.token = response['token']
self.headers['Authorization'] = f'Bearer {self.token}'
return self.token
return response

def get_account_by_id(self, account_id: str) -> Union[Dict, int]:
return self._make_request('GET', f'accounts/{account_id}')

def delete_account(self, account_id: str) -> Tuple[bool, int]:
response = self._make_request('DELETE', f'accounts/{account_id}')
return response == 204, response

def get_me(self) -> Union[Dict, int]:
return self._make_request('GET', 'me')

def get_email_by_token(self) -> Union[Dict, int]:
return self._make_request('GET', 'me')

def get_domains(self) -> Union[Dict, int]:
return self._make_request('GET', 'domains')

def get_domain_by_id(self, domain_id: str) -> Union[Dict, int]:
return self._make_request('GET', f'domains/{domain_id}')

def get_messages(self) -> Union[Dict, int]:
return self._make_request('GET', 'messages')

def get_message_by_id(self, message_id: str) -> Union[Dict, int]:
return self._make_request('GET', f'messages/{message_id}')

def delete_message(self, message_id: str) -> Tuple[bool, int]:
response = self._make_request('DELETE', f'messages/{message_id}')
return response == 204, response

def mark_message_read(self, message_id: str, read: bool = True) -> Tuple[bool, int]:
response = self._make_request('PATCH', f'messages/{message_id}', {'read': read})
return isinstance(response, dict), response

def get_message_attachment(self, message_id: str, attachment_id: str) -> Union[Dict, int]:
return self._make_request('GET', f'messages/{message_id}/attachment/{attachment_id}')

def download_message(self, message_id: str) -> Union[Dict, int]:
return self._make_request('GET', f'messages/{message_id}/download')

def get_source(self, source_id: str) -> Union[Dict, int]:
return self._make_request('GET', f'sources/{source_id}')
Loading

0 comments on commit 96b1f62

Please sign in to comment.