To get an Amazon Buy Box lost alert by email, poll /amazon-product-offers for each of your ASINs, compare buyBox.sellerId with your own seller ID, and send one email over SMTP only when the same reading shows up on two checks in a row. The script below sends one email per run, tells a lost Buy Box apart from a suppressed one, and tells apart an SMTP rejection (wrong credentials, a refused recipient) from a transient connection failure that is actually safe to retry.
Key Takeaways
- buyBox is the featured offer: its sellerId is the seller who holds the Buy Box, the literal "Amazon" when Amazon does.
- An empty buyBox means two different things: buyBoxSuppressed true (offers exist, Amazon features none) or no offers at all.
- Alert only when two checks in a row agree: an offer page can come back without parsable offers, and one reading should not send an email.
- sendmail() returning an empty dict means the relay accepted the message for every recipient at the protocol level, not that it was delivered to an inbox.
- SMTPAuthenticationError and a refused recipient are protocol-level rejections and are never retried; SMTPServerDisconnected and a connect timeout are transport failures and are retried with backoff.
What does the offers endpoint tell you about who holds the Buy Box?
/amazon-product-offers reads one page of the live offer listing. buyBox is the featured offer with sellerId, sellerName and totalPrice; Amazon itself appears as the literal "Amazon" with its own ID. When buyBox is an empty object, buyBoxSuppressed says why: true means offers exist but Amazon shows no featured offer, false with an empty offers list means there is nothing to feature. The script maps every response to one of four readings; any holder other than you is the same lost reading, so a Buy Box that rotates between two other sellers still confirms a loss. Field details are in the Offer Listing API guide.
| Response | Reading | |
|---|---|---|
| buyBox.sellerId is your sellerId | mine | BACK, after a confirmed loss |
| buyBox.sellerId is any other seller or "Amazon" | lost | LOST, with holder, price and your offer |
| buyBox is {} and buyBoxSuppressed is true | suppressed | NONE |
| buyBox is {} and offers is [] | no-offers | NONE |
How do I build the Amazon Buy Box lost email alert?
read_buy_box() turns one offers response into a reading, check() keeps a streak per ASIN in buybox_state.json and queues a line once a new reading has been seen CONFIRM times in a row, and send_email() opens one STARTTLS connection per run and sends all queued lines in a single message. get_with_retry comes from retry.py and ApiError/new_session from sellermagnet.py, both from the Python quickstart. Malformed ASINs are skipped before any call, because the offers endpoint bills a typo like any other request. MY_SELLER_ID has no default on purpose: without it every ASIN would read as lost. The SMTP credentials use an app password, since most providers reject a plain account password over SMTP once 2-factor authentication is on.
buybox_email_alert.py - offers check, 2-check confirmation, one SMTP email per run
import json
import os
import re
import smtplib
import time
from email.mime.text import MIMEText
from retry import get_with_retry
from sellermagnet import ApiError, new_session
MARKETPLACE_ID = "ATVPDKIKX0DER" # amazon.com
MY_SELLER_ID = os.environ["MY_SELLER_ID"] # your sellerId as it appears in offers[]; no default on purpose
ASINS = ["B0CL61F39H", "B0EXAMPLE2", "B0EXAMPLE3"]
CONFIRM = 2 # same reading on 2 checks in a row before an email goes out
STATE_FILE = "buybox_state.json"
ASIN_RE = re.compile(r"\A[A-Z0-9]{10}\Z") # offers calls are billed even for a typo, so filter first
SMTP_HOST = os.environ["SMTP_HOST"]
SMTP_PORT = int(os.environ.get("SMTP_PORT", "587"))
SMTP_USER = os.environ["SMTP_USER"]
SMTP_PASSWORD = os.environ["SMTP_PASSWORD"] # an app password on providers that require 2FA, not the login password
ALERT_FROM = os.environ.get("ALERT_FROM", SMTP_USER)
ALERT_TO = os.environ["ALERT_TO"]
SMTP_RETRYABLE = (smtplib.SMTPServerDisconnected, smtplib.SMTPConnectError, ConnectionError, TimeoutError)
def read_buy_box(session, asin: str) -> tuple[str, str]:
"""('mine' | 'lost' | 'suppressed' | 'no-offers', detail for the message)."""
data = get_with_retry(session, "amazon-product-offers", asin=asin, marketplaceId=MARKETPLACE_ID)
box = data.get("buyBox") or {}
if not box:
# {} has two causes: offers exist but Amazon features none, or no offer at all (or none parsable)
return ("suppressed", "") if data.get("buyBoxSuppressed") else ("no-offers", "")
holder = box.get("sellerId") or "unknown"
if holder == MY_SELLER_ID:
return "mine", ""
currency = (data.get("currency") or {}).get("code", "")
detail = f"{box.get('sellerName', '?')} ({holder}, {box.get('fulfillmentType', '?')})"
if isinstance(box.get("totalPrice"), (int, float)): # price + shipping as floats, not rounded by the API
detail += f" at {box['totalPrice']:.2f} {currency}"
mine = [o["totalPrice"] for o in data.get("offers") or []
if o.get("sellerId") == MY_SELLER_ID and isinstance(o.get("totalPrice"), (int, float))]
detail += f", yours {min(mine):.2f}" if mine else ""
return "lost", detail # any other holder is the same reading: a rotation still confirms
def message_line(asin: str, key: str, detail: str) -> str | None:
if key == "lost":
return f"LOST {asin}: {detail}" if detail else f"LOST {asin}"
if key == "back":
return f"BACK {asin}: you hold the Buy Box again"
return None
def load_state() -> dict:
try:
with open(STATE_FILE) as f:
return json.load(f)
except FileNotFoundError:
return {}
def save_state(state: dict) -> None:
with open(STATE_FILE, "w") as f:
json.dump(state, f)
def check(state: dict, asin: str, key: str, detail: str) -> str | None:
"""Advance the per-ASIN streak; return a queued line only once a reading repeats CONFIRM times."""
entry = state.get(asin, {"streak_key": None, "streak": 0, "alerted": None})
if key == entry["streak_key"]:
entry["streak"] += 1
else:
entry = {"streak_key": key, "streak": 1, "alerted": entry["alerted"]} # keep 'alerted' across a reset
state[asin] = entry
if entry["streak"] < CONFIRM:
return None
if key == "mine":
if entry["alerted"] == "lost":
entry["alerted"] = None
return message_line(asin, "back", "")
return None
if key == "lost" and entry["alerted"] != "lost":
entry["alerted"] = "lost"
return message_line(asin, "lost", detail)
return None
def send_email(subject: str, body: str, attempts: int = 4) -> dict:
"""STARTTLS + login + sendmail. A clean send returns an EMPTY refused-dict for every recipient;
a non-empty dict means the server accepted the connection but refused one or more recipients,
which is NOT the same failure as a dropped connection and is never retried."""
msg = MIMEText(body, "plain", "utf-8")
msg["Subject"] = subject
msg["From"] = ALERT_FROM
msg["To"] = ALERT_TO
last = {"accepted": False, "refused": None, "error": "no attempt made"}
for attempt in range(1, attempts + 1):
try:
with smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=15) as server:
server.starttls()
server.login(SMTP_USER, SMTP_PASSWORD)
refused = server.sendmail(ALERT_FROM, [ALERT_TO], msg.as_string())
if not refused:
return {"accepted": True, "refused": {}, "error": None}
# a non-empty dict is a per-recipient refusal (e.g. bad address); never retryable, same as a
# 400-class HTTP response in the webhook/SMS siblings of this post
return {"accepted": False, "refused": refused, "error": "recipient(s) refused"}
except smtplib.SMTPAuthenticationError as err:
return {"accepted": False, "refused": None, "error": f"auth failed: {err}"} # never retryable
except smtplib.SMTPRecipientsRefused as err:
return {"accepted": False, "refused": err.recipients, "error": "recipient(s) refused"}
except SMTP_RETRYABLE as err:
last = {"accepted": False, "refused": None, "error": f"{type(err).__name__}: {err}"}
if attempt == attempts:
return last
time.sleep(min(2 ** attempt, 60))
return last
def main() -> None:
session = new_session()
state = load_state()
queued: list[str] = []
for asin in ASINS:
if not ASIN_RE.match(asin):
print(f"SKIP {asin}: not a well-formed ASIN, not billed")
continue
try:
key, detail = read_buy_box(session, asin)
except ApiError as err:
if err.status in (401, 403):
print(f"STOP: {err.status} on {asin}, run ended early (free, not billed)")
break
print(f"SKIP {asin}: {err.status} {err}") # 404 billed-not-retried, 502/503 billed-and-capped
continue
line = check(state, asin, key, detail)
if line:
queued.append(line)
save_state(state)
if not queued:
print(f"{len(ASINS)} checked, 0 emails sent")
return
body = "SellerMagnet Buy Box alert:\n" + "\n".join(queued)
result = send_email(f"Buy Box alert: {len(queued)} change(s)", body)
if result["accepted"]:
print("[smtp] accepted, 0 recipients refused")
else:
print(f"[smtp] NOT accepted: {result['error']}")
print(f"{len(ASINS)} checked, {len(queued)} alert(s) queued, email accepted={result['accepted']}")
if __name__ == "__main__":
main()
Environment variables the script reads
SELLERMAGNET_API_KEY=sk_live_xxxxxxxxxxxxxxxx
MY_SELLER_ID=A1B2C3D4E5F6G7
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=alerts@yourdomain.com
SMTP_PASSWORD=xxxx-xxxx-xxxx-xxxx # app password, not the account login password
ALERT_TO=you@yourdomain.com

Which SMTP failures are safe to retry?
smtplib raises a different exception for a server that answered and refused the request than for one that never completed the handshake, and only the second class is worth a retry; retrying the first gets the exact same answer and wastes the run's time budget. send_email() classifies every outcome into one of four buckets before deciding whether to retry.
| What happened | What smtplib raises / returns | What the script does |
|---|---|---|
| Clean send, 0 recipients refused | sendmail() returns {} | accepted, alert delivered to the relay |
| One or more recipients refused (bad address, blocked domain) | sendmail() returns a non-empty dict, or SMTPRecipientsRefused | NOT accepted, never retried |
| Wrong SMTP username/password | SMTPAuthenticationError | NOT accepted, never retried |
| Connection dropped mid-handshake, or a connect timeout | SMTPServerDisconnected / SMTPConnectError / ConnectionError | retried with backoff, up to 4 attempts |

Five runs over the same 3 ASINs (illustrative data)
--- run 1 (illustrative ASINs and sellers)
3 checked, 0 emails sent
--- run 2, one check later: B0EXAMPLE2's Buy Box flips (1st sighting, not confirmed yet)
3 checked, 0 emails sent
--- run 3: same reading confirmed, one email sent
[smtp] accepted, 0 recipients refused
3 checked, 1 alert(s) queued, email accepted=True
--- run 4: B0EXAMPLE2 is back (1st sighting, not confirmed yet)
3 checked, 0 emails sent
--- run 5: back-in-stock confirmed, one email sent
[smtp] accepted, 0 recipients refused
3 checked, 1 alert(s) queued, email accepted=True
Frequently Asked Questions
Does a successful sendmail() call mean the email was delivered?
No. An empty refused-dict from sendmail() means the SMTP relay accepted the message for every recipient at the protocol level (SMTP code 250 after DATA). It says nothing about what the receiving mailbox provider does next: spam-folder delivery, a later bounce, or a greylist delay are all still possible and this script does not poll for any of them.
Why does a wrong password raise a different exception than a dropped connection?
smtplib distinguishes a protocol-level rejection (SMTPAuthenticationError, SMTPRecipientsRefused) from a transport failure (SMTPServerDisconnected, SMTPConnectError, a plain ConnectionError). The first class means the server answered and said no, so a retry gets the same answer; the second means the attempt never completed, so a retry can genuinely help.
Why wait for a second check before sending the email?
An offer page can come back without parsable offers, which reads the same as a lost Buy Box. Waiting for the same reading on two checks in a row filters a one-off reading at the cost of one interval, the same convention as the Slack/SMS alert versions of this script.
Why use an app password instead of my real email password?
Gmail, Outlook and most other providers reject a plain-password SMTP login once 2-factor authentication is on, and several reject it even without 2FA as a bot-abuse measure. An app password is a separate, revocable credential scoped to SMTP access only.
Why STARTTLS on port 587 instead of implicit TLS on 465?
Both are correct; this script uses STARTTLS because it is the more commonly documented default for third-party SMTP relays (SendGrid, Mailgun, Amazon SES, Gmail). An implicit-TLS relay on 465 needs smtplib.SMTP_SSL instead of SMTP() + starttls(), nothing else in the script changes.
What happens when my SellerMagnet credits run out?
The API answers 401 (or 403 during a burst), which is not billed. The script stops instead of calling the remaining ASINs and sends no email for that run.
Bottom line: an Amazon Buy Box lost alert by email needs the same two-check confirmation as its Slack and SMS siblings, plus one extra distinction those channels do not need: telling an SMTP server's own rejection (bad credentials, a refused recipient) apart from a transport failure that a retry can actually fix. Confirm, classify, then send once per run.