Python SDK for api.anymessage.shop — temporary and long-term email automation
Project description
AnyMessage SDK
A lightweight Python SDK for the https://anymessage.shop API.
Supports short-term and long-term mailboxes, automatic message polling, and Activation Rate management.
Installation
pip install anymessage-sdk
Requires Python 3.8+ and requests.
Getting your API token
- Register at anymessage.shop
- Go to your personal account dashboard
- Copy your API token
Quick Start
from anymessage import AnyMessageClient
with AnyMessageClient("YOUR_TOKEN") as client:
order = client.order_email(site="instagram.com", domain="gmx,mailcom")
msg = client.wait_for_message(id=order.id, timeout=120, poll_interval=3)
client.cancel_email(id=order.id)
print("Email:", order.email)
print("HTML:", (msg.html or "")[:400])
Or use the one-liner combo that orders, waits, and extracts a value with regex:
activation_id, email, html, code = client.order_wait_and_extract(
site="instagram.com",
domain="gmx,mailcom",
regex=r"(\d{6})", # extract 6-digit code from the email body
timeout=120,
)
print(f"Code: {code}") # e.g. "482910"
Short-term Emails
| Method | Description |
|---|---|
get_balance() |
Get account balance |
get_email_quantity(site) |
Available domains and counts |
order_email(site, domain, regex=None, subject=None) |
Order a temporary email |
reorder_email(id=None, email=None, site=None) |
Repeat a previous order |
get_message(id, preview=False) |
Fetch a message (raises WaitMessageError if not yet arrived) |
wait_for_message(id, timeout=120, poll_interval=2, preview=False, on_tick=None, stop_event=None) |
Poll until message arrives |
cancel_email(id) |
Cancel an activation |
order_wait_and_extract(site, domain, regex=None, subject=None, timeout=180, ...) |
Combo: order → wait → extract; returns (id, email, html, match_or_None) |
Domain aggregators — pass multiple domains as a comma-separated string or a list; the API returns whichever has stock:
client.order_email(site="instagram.com", domain="gmx,mailcom,hotmail")
client.order_email(site="instagram.com", domain=["gmx", "mailcom"])
Long-term Emails
| Method | Description |
|---|---|
get_longlive_quantity(site) |
Available domains with counts and prices |
order_longlive_email(site, domain, count=1) |
Buy 1–1000 mailboxes; returns LongliveOrderResponse |
get_longlive_history(offset=1, limit=10) |
Order history with IMAP credentials |
get_longlive_last_messages(id, subject=None) |
Messages from the last 40 minutes |
get_longlive_messages(id, created_at=None, subject=None) |
All messages for an activation |
find_longlive_email(email) |
Look up a purchased mailbox by address |
# Check what's available
qty = client.get_longlive_quantity(site="instagram.com")
print(qty.data) # {"hotmail.com": {"count": 93, "price": 0.006}, ...}
# Buy 5 mailboxes at once
resp = client.order_longlive_email(site="instagram.com", domain="hotmail.com", count=5)
print(f"Bought {resp.count}, total ${resp.total_price}")
for mailbox in resp.emails:
print(mailbox.email, mailbox.imap.password, mailbox.imap.link, mailbox.imap.port)
# Fetch recent messages for one of the mailboxes
msgs = client.get_longlive_last_messages(id=resp.emails[0].id)
for m in msgs:
print(m.subject, m.from_, m.message[:200])
# Find a previously purchased mailbox
records = client.find_longlive_email(email="example@hotmail.com")
if records:
print(records[0]["id"], records[0]["imap"])
Activation Rate
| Method | Description |
|---|---|
get_ratio(full=False) |
Cancel statistics per site+domain pair |
enable_block_ratio() |
Auto-block orders when ratio drops below threshold |
disable_block_ratio() |
Disable auto-blocking |
# By default only shows pairs with cancel rate >= 60%
# Pass full=True to see all pairs including healthy ones
for entry in client.get_ratio(full=True):
print(f"{entry.site} / {entry.domain}: ratio={entry.ratio:.2f}, cancel%={entry.cancel_percent}")
When blocking is enabled and the cancel rate reaches ≥ 60%, order_email raises RatioBlockError.
Error Handling
from anymessage import (
AnyMessageClient, AnyMessageError,
AuthError, NoBalanceError, NoEmailsError,
RatioBlockError, ActivationCanceledError,
)
try:
with AnyMessageClient("YOUR_TOKEN") as c:
order = c.order_email(site="instagram.com", domain="gmx")
msg = c.wait_for_message(id=order.id, timeout=120)
except AuthError:
print("Invalid token")
except NoBalanceError:
print("Insufficient balance")
except NoEmailsError:
print("No emails available for this site/domain")
except RatioBlockError:
print("Blocked due to low Activation Rate")
except ActivationCanceledError:
print("Activation was canceled")
except AnyMessageError as e:
print("API error:", e)
Full exception list: AuthError, ValidationError, NotFoundError, NoBalanceError, NoEmailsError, ActivationCanceledError, ActivationAlreadyCanceledError, EmailBannedError, WaitMessageError, RatioBlockError.
Implementation Details
- Uses
requests.Sessionwith automatic retries (urllib3) and connection pooling. - Thread-safe: create a separate
AnyMessageClientper thread or task. - No temporary files — everything runs in memory.
wait_for_messagesupportson_tick(n)progress callback andstop_event(any object with.is_set()) for cancellation from another thread.
License
MIT License © 2025 AnyMessage SDK contributors
API Documentation: https://anymessage.shop/en/docs
Official Website: https://anymessage.shop/en
AnyMessage SDK (Русский)
Лёгкий Python-SDK для работы с API https://anymessage.shop.
Поддерживает краткосрочные и долгосрочные почты, автоматическое ожидание письма и управление Activation Rate.
Установка
pip install anymessage-sdk
Требуется Python 3.8+ и requests.
Где взять токен
- Зарегистрируйтесь на anymessage.shop
- Зайдите в личный кабинет
- Скопируйте ваш API-токен
Быстрый старт
from anymessage import AnyMessageClient
with AnyMessageClient("ВАШ_ТОКЕН") as client:
order = client.order_email(site="instagram.com", domain="gmx,mailcom")
msg = client.wait_for_message(id=order.id, timeout=120, poll_interval=3)
client.cancel_email(id=order.id)
print("Email:", order.email)
print("HTML:", (msg.html or "")[:400])
Или однострочное комбо — заказать, дождаться и извлечь значение по regex:
activation_id, email, html, code = client.order_wait_and_extract(
site="instagram.com",
domain="gmx,mailcom",
regex=r"(\d{6})", # извлечь 6-значный код из тела письма
timeout=120,
)
print(f"Код: {code}") # например "482910"
Краткосрочные почты
| Метод | Описание |
|---|---|
get_balance() |
Баланс аккаунта |
get_email_quantity(site) |
Доступные домены и количество |
order_email(site, domain, regex=None, subject=None) |
Заказать почту |
reorder_email(id=None, email=None, site=None) |
Повторный заказ |
get_message(id, preview=False) |
Получить письмо (бросает WaitMessageError если ещё не пришло) |
wait_for_message(id, timeout=120, poll_interval=2, preview=False, on_tick=None, stop_event=None) |
Ожидать письмо с поллингом |
cancel_email(id) |
Отменить активацию |
order_wait_and_extract(site, domain, regex=None, subject=None, timeout=180, ...) |
Комбо: заказать → дождаться → извлечь; возвращает (id, email, html, совпадение_или_None) |
Агрегаторы доменов — можно передать несколько через запятую или списком; API вернёт тот, у которого есть остаток:
client.order_email(site="instagram.com", domain="gmx,mailcom,hotmail")
client.order_email(site="instagram.com", domain=["gmx", "mailcom"])
Долгосрочные почты
| Метод | Описание |
|---|---|
get_longlive_quantity(site) |
Доступные домены с количеством и ценами |
order_longlive_email(site, domain, count=1) |
Купить 1–1000 ящиков; возвращает LongliveOrderResponse |
get_longlive_history(offset=1, limit=10) |
История заказов с IMAP-данными |
get_longlive_last_messages(id, subject=None) |
Письма за последние 40 минут |
get_longlive_messages(id, created_at=None, subject=None) |
Все письма активации |
find_longlive_email(email) |
Найти купленный ящик по адресу |
# Посмотреть что доступно
qty = client.get_longlive_quantity(site="instagram.com")
print(qty.data) # {"hotmail.com": {"count": 93, "price": 0.006}, ...}
# Купить 5 ящиков сразу
resp = client.order_longlive_email(site="instagram.com", domain="hotmail.com", count=5)
print(f"Куплено: {resp.count}, итого ${resp.total_price}")
for mailbox in resp.emails:
print(mailbox.email, mailbox.imap.password, mailbox.imap.link, mailbox.imap.port)
# Получить свежие письма одного из ящиков
msgs = client.get_longlive_last_messages(id=resp.emails[0].id)
for m in msgs:
print(m.subject, m.from_, m.message[:200])
# Найти ранее купленный ящик
records = client.find_longlive_email(email="example@hotmail.com")
if records:
print(records[0]["id"], records[0]["imap"])
Activation Rate
| Метод | Описание |
|---|---|
get_ratio(full=False) |
Статистика отмен по парам сайт+домен |
enable_block_ratio() |
Включить автоблокировку при низком рейтинге |
disable_block_ratio() |
Отключить автоблокировку |
# По умолчанию показывает только пары с долей отмен >= 60%
# full=True — все пары включая здоровые
for entry in client.get_ratio(full=True):
print(f"{entry.site} / {entry.domain}: ratio={entry.ratio:.2f}, cancel%={entry.cancel_percent}")
При включённой блокировке и доле отмен ≥ 60% вызов order_email бросает RatioBlockError.
Обработка ошибок
from anymessage import (
AnyMessageClient, AnyMessageError,
AuthError, NoBalanceError, NoEmailsError,
RatioBlockError, ActivationCanceledError,
)
try:
with AnyMessageClient("ВАШ_ТОКЕН") as c:
order = c.order_email(site="instagram.com", domain="gmx")
msg = c.wait_for_message(id=order.id, timeout=120)
except AuthError:
print("Неверный токен")
except NoBalanceError:
print("Недостаточно средств")
except NoEmailsError:
print("Нет доступных почт для этого сайта/домена")
except RatioBlockError:
print("Заблокировано из-за низкого Activation Rate")
except ActivationCanceledError:
print("Активация была отменена")
except AnyMessageError as e:
print("Ошибка API:", e)
Полный список исключений: AuthError, ValidationError, NotFoundError, NoBalanceError, NoEmailsError, ActivationCanceledError, ActivationAlreadyCanceledError, EmailBannedError, WaitMessageError, RatioBlockError.
Детали реализации
requests.Sessionс автоматическими ретраями (urllib3) и пулом соединений.- Потокобезопасно: создавайте отдельный
AnyMessageClientна поток или задачу. - Без временных файлов — всё в памяти.
wait_for_messageподдерживает колбэкon_tick(n)для отображения прогресса иstop_event(любой объект с.is_set()) для отмены из другого потока.
Лицензия
MIT License © 2025 AnyMessage SDK contributors
Документация API: https://anymessage.shop/ru/docs
Официальный сайт: https://anymessage.shop/ru
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file anymessage_sdk-0.2.2.tar.gz.
File metadata
- Download URL: anymessage_sdk-0.2.2.tar.gz
- Upload date:
- Size: 23.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
706c7ad9027e65e40d29eb95707374d262078312e0efbefea4bef8325ae2bdb8
|
|
| MD5 |
ac62e48f62cf1d99fbfbc36f024a52a2
|
|
| BLAKE2b-256 |
546fda1bf0947287bca15516601d3a217b388861f682d4cf5413631649cb03b2
|
File details
Details for the file anymessage_sdk-0.2.2-py3-none-any.whl.
File metadata
- Download URL: anymessage_sdk-0.2.2-py3-none-any.whl
- Upload date:
- Size: 23.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b7f42361519074ffd4ada43ef82e9d80882e4f0e80597a064476bc11a612aa3c
|
|
| MD5 |
7a91e00c7edc361fe857db01d12d52a6
|
|
| BLAKE2b-256 |
b03f30baeb8b4800f93fa6515b556d4c2337f00e9dedd5bff5a9570ecc3fd69a
|