Skip to main content

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.


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.Session with automatic retries (urllib3) and connection pooling.
  • Thread-safe: create a separate AnyMessageClient per thread or task.
  • No temporary files — everything runs in memory.
  • wait_for_message supports on_tick(n) progress callback and stop_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.


Быстрый старт

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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

anymessage_sdk-0.2.1.tar.gz (22.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

anymessage_sdk-0.2.1-py3-none-any.whl (23.4 kB view details)

Uploaded Python 3

File details

Details for the file anymessage_sdk-0.2.1.tar.gz.

File metadata

  • Download URL: anymessage_sdk-0.2.1.tar.gz
  • Upload date:
  • Size: 22.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.0

File hashes

Hashes for anymessage_sdk-0.2.1.tar.gz
Algorithm Hash digest
SHA256 cd2b26b79413d84a89c34fdc7ed32096387c12223947e4579611e76134e7ad99
MD5 195f6d663a5157e29710965cbfddfc96
BLAKE2b-256 9d1f3aabccc2004ec30829974e43f69fc894e1599ed84cf6be54dca27580c7d9

See more details on using hashes here.

File details

Details for the file anymessage_sdk-0.2.1-py3-none-any.whl.

File metadata

  • Download URL: anymessage_sdk-0.2.1-py3-none-any.whl
  • Upload date:
  • Size: 23.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.0

File hashes

Hashes for anymessage_sdk-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 629b1eee82a6e0e046e31cfbeb6f0656833e2499a89c5cdade4591f824de9e2b
MD5 ecbaaca02379494a5933f4b12a63fee9
BLAKE2b-256 0115c57ed416f35906d1b3751f1dc67c381d74c124710450d38657dd7f58aae0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page