Skip to content

Python API Reference

ZohoMailClient

zohomail.client.ZohoMailClient

Async Zoho Mail client for free-tier accounts.

Authenticates via the Zoho web UI using Playwright, then communicates with Zoho's internal JSON API (ml.do / md.do). The session cookie is cached at ~/.zohomail_session.pkl and reused on subsequent calls. If the session expires the client re-authenticates automatically.

Parameters:

Name Type Description Default
email str

Your Zoho Mail address (e.g. you@yourdomain.com).

required
password str

Your Zoho account login password (not an app password).

required
region str

Zoho data-centre region — "eu" (default) or "com".

'eu'
account_id str

Internal Zoho account ID. Auto-discovered if omitted.

''
folder_id str

Internal Zoho inbox folder ID. Auto-discovered if omitted.

''
session_file Path | None

Path for the session cookie cache. Defaults to ~/.zohomail_session.pkl.

None
Example

client = ZohoMailClient( ... email="you@yourdomain.com", ... password="your_password", ... region="eu", ... ) emails = asyncio.run(client.list_emails(limit=10))

Source code in zohomail/client.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
class ZohoMailClient:
    """Async Zoho Mail client for free-tier accounts.

    Authenticates via the Zoho web UI using Playwright, then communicates
    with Zoho's internal JSON API (``ml.do`` / ``md.do``). The session
    cookie is cached at ``~/.zohomail_session.pkl`` and reused on subsequent
    calls. If the session expires the client re-authenticates automatically.

    Args:
        email: Your Zoho Mail address (e.g. ``you@yourdomain.com``).
        password: Your Zoho account login password (not an app password).
        region: Zoho data-centre region — ``"eu"`` (default) or ``"com"``.
        account_id: Internal Zoho account ID. Auto-discovered if omitted.
        folder_id: Internal Zoho inbox folder ID. Auto-discovered if omitted.
        session_file: Path for the session cookie cache. Defaults to
            ``~/.zohomail_session.pkl``.

    Example:
        >>> client = ZohoMailClient(
        ...     email="you@yourdomain.com",
        ...     password="your_password",
        ...     region="eu",
        ... )
        >>> emails = asyncio.run(client.list_emails(limit=10))
    """

    def __init__(
        self,
        email: str,
        password: str,
        region: str = "eu",
        account_id: str = "",
        folder_id: str = "",
        session_file: Path | None = None,
    ):
        self.email = email
        self.password = password
        self.region = region.lower()
        self.account_id = account_id
        self.folder_id = folder_id
        self.session_file = session_file or SESSION_FILE
        self._ml_host: str = ""
        self._inbox_data = None

    @property
    def _mail_url(self) -> str:
        return f"https://mail.zoho.{'eu' if self.region == 'eu' else 'com'}"

    @property
    def _accounts_url(self) -> str:
        return f"https://accounts.zoho.{'eu' if self.region == 'eu' else 'com'}"

    # ── internal ──────────────────────────────────────────────────────────────

    async def _make_context(self, p):
        browser = await p.chromium.launch(
            headless=True,
            args=[
                "--no-sandbox",
                "--disable-setuid-sandbox",
                "--disable-dev-shm-usage",
                "--disable-gpu",
                "--disable-gpu-sandbox",
                "--single-process",
                "--no-zygote",
                "--use-gl=swiftshader-webgl",
                "--disable-software-rasterizer",
                "--disable-accelerated-2d-canvas",
                "--disable-webgl",
            ],
        )
        ctx = await browser.new_context()
        if self.session_file.exists():
            try:
                cookies = pickle.loads(self.session_file.read_bytes())
                await ctx.add_cookies(cookies)
            except Exception:
                pass
        return browser, ctx

    async def _login(self, page, ctx):
        await page.goto(f"{self._accounts_url}/signin?servicename=ZohoMail")
        await page.wait_for_load_state("domcontentloaded")
        await page.fill("#login_id", self.email)
        await page.click("#nextbtn")
        await page.wait_for_timeout(2000)
        await page.fill("#password", self.password)
        await page.click("#nextbtn")
        await page.wait_for_timeout(4000)
        if "announcement" in page.url or "tfa-banner" in page.url:
            for btn in ["Continue", "I Understand", "Proceed", "OK", "Allow", "Confirm"]:
                try:
                    await page.click(f"text={btn}", timeout=2000)
                    await page.wait_for_timeout(3000)
                    break
                except Exception:
                    pass
        if "/signin" in page.url and "signin-block" not in page.url:
            raise ZohoMailError("Login failed — check ZOHO_EMAIL and ZOHO_PASSWORD")
        cookies = await ctx.cookies()
        self.session_file.write_bytes(pickle.dumps(cookies))

    async def _get_page(self, p):
        browser, ctx = await self._make_context(p)
        page = await ctx.new_page()
        self._inbox_data = None

        async def on_response(res):
            if "ml.do" in res.url:
                parsed = urlparse(res.url)
                qs = parse_qs(parsed.query)
                self.account_id = self.account_id or (qs.get("accId") or [""])[0]
                self.folder_id  = self.folder_id  or (qs.get("folId") or [""])[0]
                self._ml_host   = parsed.netloc
                try:
                    self._inbox_data = await res.json()
                except Exception:
                    pass

        page.on("response", on_response)

        async def _goto_mail(ml_timeout=180.0):
            # The mail SPA fires the listing call (ml.do) long after
            # domcontentloaded, and this browser runs --single-process, so the
            # whole app boots on one thread. Deep-link the inbox route (the bare
            # /zm/ shell often sits idle) and wait on _ml_host, which
            # on_response sets when the call actually goes out.
            try:
                await page.goto(
                    f"{self._mail_url}/zm/#mail/folder/inbox",
                    wait_until="domcontentloaded",
                    timeout=30000,
                )
            except Exception:
                pass
            deadline = time.monotonic() + ml_timeout
            while not self._ml_host and time.monotonic() < deadline:
                if "/signin" in page.url or "accounts.zoho" in page.url:
                    return  # session is gone; the caller re-logins
                await page.wait_for_timeout(500)

        if not self.session_file.exists():
            # No cached session — go straight to login, skip the mail probe
            await self._login(page, ctx)

        await _goto_mail()

        if "/signin" in page.url or "accounts.zoho" in page.url:
            # Cached session expired — clear and re-login
            if self.session_file.exists():
                self.session_file.unlink()
            await self._login(page, ctx)
            self._inbox_data = None
            await _goto_mail()

        # A cold boot occasionally never fires ml.do (seen 2026-11-16 with the
        # 180 s wait): reload the route once; the warm cache boots faster.
        if not self._ml_host and not ("/signin" in page.url or "accounts.zoho" in page.url):
            try:
                await page.reload(wait_until="domcontentloaded", timeout=30000)
            except Exception:
                pass
            deadline = time.monotonic() + 180.0
            while not self._ml_host and time.monotonic() < deadline:
                await page.wait_for_timeout(500)

        if not self._ml_host:
            raise ZohoMailError(
                "Could not discover Zoho API host. "
                "The page may not have loaded correctly."
            )

        return browser, page

    async def _fetch(self, page, url: str, params: dict):
        qs = "&".join(f"{k}={v}" for k, v in params.items())
        full = f"{url}?{qs}"
        result = await page.evaluate(f"""async () => {{
            const r = await fetch({json.dumps(full)}, {{credentials: 'include'}});
            if (!r.ok) throw new Error('HTTP ' + r.status);
            return await r.text();
        }}""")
        if not result:
            raise ZohoMailError(f"Empty response from {url}")
        try:
            return json.loads(result)
        except json.JSONDecodeError:
            raise ZohoMailError(f"Unexpected response from Zoho API: {result[:200]}")

    def _ml_url(self) -> str:
        if not self._ml_host:
            raise ZohoMailError("API host not yet discovered — call list_emails first")
        return f"https://{self._ml_host}/zm/ml.do"

    def _md_url(self) -> str:
        if not self._ml_host:
            raise ZohoMailError("API host not yet discovered — call list_emails first")
        return f"https://{self._ml_host}/zm/md.do"

    # ── public API ────────────────────────────────────────────────────────────


    async def _resolve_folder(self, page, folder: str | None) -> str:
        """Map a folder name ("Inbox", "Sent", "Drafts", "Spam"...) to its folId.

        Zoho's SPA keeps the tree at window.zmail.folTree[0] keyed by folId,
        each entry carrying the display name in FN. None/"" keeps the inbox id
        discovered at page load, so existing callers are unchanged."""
        if not folder or folder.lower() == "inbox":
            return self.folder_id
        fid = await page.evaluate(
            """(name) => {
                const t = (window.zmail && window.zmail.folTree && window.zmail.folTree[0]) || {};
                const want = name.toLowerCase();
                for (const k of Object.keys(t)) {
                    const fn = String((t[k] && t[k].FN) || "").toLowerCase();
                    if (fn === want || fn === want + " items" || fn === want + " mail") return k;
                }
                return "";
            }""", folder)
        if not fid:
            raise ZohoMailError(f"folder not found in Zoho folder tree: {folder!r}")
        return fid

    async def list_emails(self, limit: int = 10, folder: str | None = None,
                          conversations: bool = False) -> list[dict]:
        """List the most recent inbox messages.

        Authenticates if needed, then returns a list of email summaries
        sorted newest-first. The inbox data is captured from network traffic
        during page load, so no extra API call is made.

        Args:
            limit: Maximum number of messages to return. Defaults to ``10``,
                max ``50``.

        Returns:
            A list of dicts, each containing:

            - ``id`` (*str*) — Zoho message ID, used with :meth:`read_email`.
            - ``from`` (*str*) — Sender email address.
            - ``subject`` (*str*) — Message subject.
            - ``time_ms`` (*int*) — Epoch ms. For a message that belongs to a
                thread Zoho reports the thread's last activity here, not the
                message's own time, so treat it as approximate and read the
                message for its true ``Date`` header.
            - ``to`` (*str*) — Recipient, useful in Sent.
            - ``unread`` (*bool*) — ``True`` if the message is unread.

        Raises:
            ZohoMailError: If authentication or the API call fails.

        Example:
            >>> emails = asyncio.run(client.list_emails(limit=5))
            >>> for e in emails:
            ...     print(e["subject"], "-", e["from"])
        """
        async with async_playwright() as p:
            browser, page = await self._get_page(p)
            try:
                # Never reuse the page-load capture here: the SPA fires several
                # ml.do calls and the last one may be a different view (Unread,
                # a smart folder), which silently returns a stale/partial inbox.
                # Always ask for the range we actually want, newest first.
                fol_id = await self._resolve_folder(page, folder)
                # folderSpec 0 lists every individual message; 2 is Zoho's
                # conversation view, where a reply of ours is folded into the
                # thread row and its sender/subject are the counterparty's. That
                # view silently hides sent replies, so it is not the default.
                data = await self._fetch(page, self._ml_url(), {
                    "xhr": int(time.time() * 1000), "mode": "listing",
                    "accId": self.account_id, "from": 1, "to": limit,
                    "summary": "true", "sortBy": "date", "sortOrder": "false",
                    "folderSpec": 2 if conversations else 0, "folId": fol_id,
                })
                msgs = [m for m in data[1] if isinstance(m, dict) and "M" in m]
                return [
                    {
                        "id":      m["M"],
                        "from":    m.get("F", ""),
                        "subject": m.get("SB", ""),
                        # LTIME is the message's own time for a standalone
                        # message, but the thread's last activity for one that
                        # belongs to a thread. Approximate by design; read_email
                        # returns the true Date header.
                        "time_ms": _first_epoch_ms(m, "LTIME", "R", "ST"),
                        "unread":  m.get("RS", 1) != 1,
                        # TOADDR is the recipient; T is the thread id and is
                        # not an address, so it must never be used as a fallback.
                        "to":      _unescape(m.get("TOADDR") or m.get("TO") or ""),
                    }
                    for m in msgs[:limit]
                ]
            finally:
                await browser.close()

    async def read_email(self, msg_id: str, folder: str | None = None) -> dict:
        """Read the full content of a single email.

        Fetches the complete message including HTML body, sender details,
        and threading headers needed for replies.

        Args:
            msg_id: The Zoho message ID (``id`` field from :meth:`list_emails`).

        Returns:
            A dict containing:

            - ``id`` (*str*) — Zoho message ID.
            - ``from`` (*str*) — Sender email address.
            - ``reply_to`` (*str*) — Address to send replies to.
            - ``to`` (*str*) — Recipient address.
            - ``date`` (*str*) — Human-readable sent date.
            - ``subject`` (*str*) — Message subject.
            - ``message_id`` (*str*) — RFC 2822 Message-ID for threading.
            - ``body`` (*str*) — Plain-text body (stripped from HTML).
            - ``body_html`` (*str*) — Raw HTML body.
            - ``attachments`` (*list[dict]*) — One entry per attachment with
                ``name``, ``format``, ``size_bytes``, ``part_id``,
                ``attachment_id``, and ``inline``. Empty list if none.

        Raises:
            ZohoMailError: If authentication or the API call fails.

        Example:
            >>> email = asyncio.run(client.read_email("1782000221530004400"))
            >>> print(email["body"])
        """
        async with async_playwright() as p:
            browser, page = await self._get_page(p)
            try:
                return await self._read_in_page(page, msg_id, folder)
            finally:
                await browser.close()

    async def _read_in_page(self, page, msg_id: str, folder: str | None) -> dict:
        fol_id = await self._resolve_folder(page, folder)
        inbox = await self._fetch(page, self._ml_url(), {
            "xhr": int(time.time() * 1000), "mode": "listing",
            "accId": self.account_id, "from": 1, "to": 50,
            "summary": "true", "sortBy": "date", "sortOrder": "false",
            "folderSpec": 0, "folId": fol_id,
        })
        row = next(
            (m for m in inbox[1] if isinstance(m, dict) and m.get("M") == msg_id),
            {},
        )
        mail_id = row.get("MAILID", "")
        data = await self._fetch(page, self._md_url(), {
            "xhr": int(time.time() * 1000), "accId": self.account_id,
            "summary": "true", "msgId": msg_id, "vfc": "false",
            "split": "true", "folId": fol_id, "mailId": mail_id,
        })
        md = data[1]["mdata"]
        html = md.get("CONTENT", "")
        return {
            "id":          msg_id,
            "from":        html_lib.unescape(md.get("FROM", "")),
            "reply_to":    html_lib.unescape(md.get("REPLYTO") or md.get("FROM", "")),
            "to":          html_lib.unescape(md.get("DELIVEREDTO", "")),
            "date":        md.get("SENTTIME", ""),
            # md.do returns SB empty for some messages; the listing row has it.
            "subject":     html_lib.unescape(md.get("SB") or row.get("SB", "")),
            "message_id":  md.get("MAILID", ""),
            "body":        strip_html(html) if html else "",
            "body_html":   html,
            "attachments": _parse_attachments(md),
        }

    async def download_attachments(self, msg_id: str, dest_dir: str | Path, folder: str | None = None,
                                   include_inline: bool = False) -> list[Path]:
        """Download a message's attachments into ``dest_dir``.

        Metadata and session cookies are collected inside the browser, the
        browser is closed, and the files are then fetched over plain HTTP with
        those cookies (Chromium runs ``--single-process``, which breaks
        in-browser request APIs). TLS is always verified; see ``_ssl_context``
        for how the CA bundle is chosen.

        Args:
            msg_id: Zoho message ID.
            dest_dir: Directory to save into (created if missing).
            folder: Folder the message lives in (default Inbox).
            include_inline: Also download inline images. Skipped by default.

        Returns:
            Saved file paths. Files keep their names; duplicates get
            `` (1)``, `` (2)`` suffixes. Empty list if there is nothing to save.

        Raises:
            ZohoMailError: On auth, API, TLS or download failure, or if a
                downloaded file's size differs from Zoho's metadata.
        """
        async with async_playwright() as p:
            browser, page = await self._get_page(p)
            try:
                msg = await self._read_in_page(page, msg_id, folder)
                cookies = await page.context.cookies()
                sid = ""
                # The SPA sets its session id a little after the listing call;
                # reading it too early gives "" and large files answer HTTP 401.
                for _ in range(180):
                    try:
                        sid = await page.evaluate(
                            "() => (window.zmail && window.zmail._ws "
                            "&& window.zmail._ws.sessionId) || ''")
                    except Exception:
                        sid = ""
                    if sid:
                        break
                    await page.wait_for_timeout(500)
            finally:
                await browser.close()

        atts = [a for a in msg["attachments"]
                if a["attachment_id"] and (include_inline or not a["inline"])]
        if not atts:
            return []
        if not sid:
            # Verified 2026-12-02: without the sid header Zoho answers HTTP 401
            # even for a 73 KB file, so fail with the real cause.
            raise ZohoMailError(
                "Web client session id (sid) not available after 90 s; "
                "downloads need it. Try again.")

        dest = Path(dest_dir)
        dest.mkdir(parents=True, exist_ok=True)
        tld = "eu" if self.region == "eu" else "com"
        # Only cookies a browser would send to the download host. Sending the
        # mail.zoho / accounts.zoho host cookies too makes it answer HTTP 401.
        host = f"zmdownload-accl.zoho.{tld}"
        cookie_header = "; ".join(
            f"{c['name']}={c['value']}" for c in cookies
            if _cookie_matches(c.get("domain", ""), host)
        )
        saved: list[Path] = []
        for i, a in enumerate(atts, 1):
            qs = urlencode({
                "pd": f"mail.zoho.{tld}", "entityType": 1, "entityId": msg_id,
                "attachId": a["attachment_id"], "accId": self.account_id,
                "checkOffline": "true",
            })
            url = f"https://{host}/normalDownload?{qs}"
            data = await asyncio.to_thread(
                _http_download, url, cookie_header, self._mail_url + "/",
                sid=sid or "")
            if a["size_bytes"] and len(data) != a["size_bytes"]:
                raise ZohoMailError(
                    f"Size mismatch for {a['name']!r}: got {len(data)} bytes, "
                    f"Zoho metadata says {a['size_bytes']}")
            path = _unique_path(dest, _safe_filename(a["name"], f"attachment-{i}"))
            path.write_bytes(data)
            saved.append(path)
        return saved

    async def get_thread_info(self, msg_id: str) -> dict:
        """Return the minimal headers needed to reply to a message.

        A lightweight alternative to :meth:`read_email` when you only need
        to send a reply and don't need the body.

        Args:
            msg_id: The Zoho message ID.

        Returns:
            A dict with ``reply_to``, ``subject``, and ``message_id`` keys.

        Raises:
            ZohoMailError: If authentication or the API call fails.
        """
        email = await self.read_email(msg_id)
        return {
            "reply_to":   email["reply_to"],
            "subject":    email["subject"],
            "message_id": email["message_id"],
        }

download_attachments(msg_id, dest_dir, folder=None, include_inline=False) async

Download a message's attachments into dest_dir.

Metadata and session cookies are collected inside the browser, the browser is closed, and the files are then fetched over plain HTTP with those cookies (Chromium runs --single-process, which breaks in-browser request APIs). TLS is always verified; see _ssl_context for how the CA bundle is chosen.

Parameters:

Name Type Description Default
msg_id str

Zoho message ID.

required
dest_dir str | Path

Directory to save into (created if missing).

required
folder str | None

Folder the message lives in (default Inbox).

None
include_inline bool

Also download inline images. Skipped by default.

False

Returns:

Type Description
list[Path]

Saved file paths. Files keep their names; duplicates get

list[Path]

(1), (2) suffixes. Empty list if there is nothing to save.

Raises:

Type Description
ZohoMailError

On auth, API, TLS or download failure, or if a downloaded file's size differs from Zoho's metadata.

Source code in zohomail/client.py
async def download_attachments(self, msg_id: str, dest_dir: str | Path, folder: str | None = None,
                               include_inline: bool = False) -> list[Path]:
    """Download a message's attachments into ``dest_dir``.

    Metadata and session cookies are collected inside the browser, the
    browser is closed, and the files are then fetched over plain HTTP with
    those cookies (Chromium runs ``--single-process``, which breaks
    in-browser request APIs). TLS is always verified; see ``_ssl_context``
    for how the CA bundle is chosen.

    Args:
        msg_id: Zoho message ID.
        dest_dir: Directory to save into (created if missing).
        folder: Folder the message lives in (default Inbox).
        include_inline: Also download inline images. Skipped by default.

    Returns:
        Saved file paths. Files keep their names; duplicates get
        `` (1)``, `` (2)`` suffixes. Empty list if there is nothing to save.

    Raises:
        ZohoMailError: On auth, API, TLS or download failure, or if a
            downloaded file's size differs from Zoho's metadata.
    """
    async with async_playwright() as p:
        browser, page = await self._get_page(p)
        try:
            msg = await self._read_in_page(page, msg_id, folder)
            cookies = await page.context.cookies()
            sid = ""
            # The SPA sets its session id a little after the listing call;
            # reading it too early gives "" and large files answer HTTP 401.
            for _ in range(180):
                try:
                    sid = await page.evaluate(
                        "() => (window.zmail && window.zmail._ws "
                        "&& window.zmail._ws.sessionId) || ''")
                except Exception:
                    sid = ""
                if sid:
                    break
                await page.wait_for_timeout(500)
        finally:
            await browser.close()

    atts = [a for a in msg["attachments"]
            if a["attachment_id"] and (include_inline or not a["inline"])]
    if not atts:
        return []
    if not sid:
        # Verified 2026-12-02: without the sid header Zoho answers HTTP 401
        # even for a 73 KB file, so fail with the real cause.
        raise ZohoMailError(
            "Web client session id (sid) not available after 90 s; "
            "downloads need it. Try again.")

    dest = Path(dest_dir)
    dest.mkdir(parents=True, exist_ok=True)
    tld = "eu" if self.region == "eu" else "com"
    # Only cookies a browser would send to the download host. Sending the
    # mail.zoho / accounts.zoho host cookies too makes it answer HTTP 401.
    host = f"zmdownload-accl.zoho.{tld}"
    cookie_header = "; ".join(
        f"{c['name']}={c['value']}" for c in cookies
        if _cookie_matches(c.get("domain", ""), host)
    )
    saved: list[Path] = []
    for i, a in enumerate(atts, 1):
        qs = urlencode({
            "pd": f"mail.zoho.{tld}", "entityType": 1, "entityId": msg_id,
            "attachId": a["attachment_id"], "accId": self.account_id,
            "checkOffline": "true",
        })
        url = f"https://{host}/normalDownload?{qs}"
        data = await asyncio.to_thread(
            _http_download, url, cookie_header, self._mail_url + "/",
            sid=sid or "")
        if a["size_bytes"] and len(data) != a["size_bytes"]:
            raise ZohoMailError(
                f"Size mismatch for {a['name']!r}: got {len(data)} bytes, "
                f"Zoho metadata says {a['size_bytes']}")
        path = _unique_path(dest, _safe_filename(a["name"], f"attachment-{i}"))
        path.write_bytes(data)
        saved.append(path)
    return saved

get_thread_info(msg_id) async

Return the minimal headers needed to reply to a message.

A lightweight alternative to :meth:read_email when you only need to send a reply and don't need the body.

Parameters:

Name Type Description Default
msg_id str

The Zoho message ID.

required

Returns:

Type Description
dict

A dict with reply_to, subject, and message_id keys.

Raises:

Type Description
ZohoMailError

If authentication or the API call fails.

Source code in zohomail/client.py
async def get_thread_info(self, msg_id: str) -> dict:
    """Return the minimal headers needed to reply to a message.

    A lightweight alternative to :meth:`read_email` when you only need
    to send a reply and don't need the body.

    Args:
        msg_id: The Zoho message ID.

    Returns:
        A dict with ``reply_to``, ``subject``, and ``message_id`` keys.

    Raises:
        ZohoMailError: If authentication or the API call fails.
    """
    email = await self.read_email(msg_id)
    return {
        "reply_to":   email["reply_to"],
        "subject":    email["subject"],
        "message_id": email["message_id"],
    }

list_emails(limit=10, folder=None, conversations=False) async

List the most recent inbox messages.

Authenticates if needed, then returns a list of email summaries sorted newest-first. The inbox data is captured from network traffic during page load, so no extra API call is made.

Parameters:

Name Type Description Default
limit int

Maximum number of messages to return. Defaults to 10, max 50.

10

Returns:

Type Description
list[dict]

A list of dicts, each containing:

list[dict]
  • id (str) — Zoho message ID, used with :meth:read_email.
list[dict]
  • from (str) — Sender email address.
list[dict]
  • subject (str) — Message subject.
list[dict]
  • time_ms (int) — Epoch ms. For a message that belongs to a thread Zoho reports the thread's last activity here, not the message's own time, so treat it as approximate and read the message for its true Date header.
list[dict]
  • to (str) — Recipient, useful in Sent.
list[dict]
  • unread (bool) — True if the message is unread.

Raises:

Type Description
ZohoMailError

If authentication or the API call fails.

Example

emails = asyncio.run(client.list_emails(limit=5)) for e in emails: ... print(e["subject"], "-", e["from"])

Source code in zohomail/client.py
async def list_emails(self, limit: int = 10, folder: str | None = None,
                      conversations: bool = False) -> list[dict]:
    """List the most recent inbox messages.

    Authenticates if needed, then returns a list of email summaries
    sorted newest-first. The inbox data is captured from network traffic
    during page load, so no extra API call is made.

    Args:
        limit: Maximum number of messages to return. Defaults to ``10``,
            max ``50``.

    Returns:
        A list of dicts, each containing:

        - ``id`` (*str*) — Zoho message ID, used with :meth:`read_email`.
        - ``from`` (*str*) — Sender email address.
        - ``subject`` (*str*) — Message subject.
        - ``time_ms`` (*int*) — Epoch ms. For a message that belongs to a
            thread Zoho reports the thread's last activity here, not the
            message's own time, so treat it as approximate and read the
            message for its true ``Date`` header.
        - ``to`` (*str*) — Recipient, useful in Sent.
        - ``unread`` (*bool*) — ``True`` if the message is unread.

    Raises:
        ZohoMailError: If authentication or the API call fails.

    Example:
        >>> emails = asyncio.run(client.list_emails(limit=5))
        >>> for e in emails:
        ...     print(e["subject"], "-", e["from"])
    """
    async with async_playwright() as p:
        browser, page = await self._get_page(p)
        try:
            # Never reuse the page-load capture here: the SPA fires several
            # ml.do calls and the last one may be a different view (Unread,
            # a smart folder), which silently returns a stale/partial inbox.
            # Always ask for the range we actually want, newest first.
            fol_id = await self._resolve_folder(page, folder)
            # folderSpec 0 lists every individual message; 2 is Zoho's
            # conversation view, where a reply of ours is folded into the
            # thread row and its sender/subject are the counterparty's. That
            # view silently hides sent replies, so it is not the default.
            data = await self._fetch(page, self._ml_url(), {
                "xhr": int(time.time() * 1000), "mode": "listing",
                "accId": self.account_id, "from": 1, "to": limit,
                "summary": "true", "sortBy": "date", "sortOrder": "false",
                "folderSpec": 2 if conversations else 0, "folId": fol_id,
            })
            msgs = [m for m in data[1] if isinstance(m, dict) and "M" in m]
            return [
                {
                    "id":      m["M"],
                    "from":    m.get("F", ""),
                    "subject": m.get("SB", ""),
                    # LTIME is the message's own time for a standalone
                    # message, but the thread's last activity for one that
                    # belongs to a thread. Approximate by design; read_email
                    # returns the true Date header.
                    "time_ms": _first_epoch_ms(m, "LTIME", "R", "ST"),
                    "unread":  m.get("RS", 1) != 1,
                    # TOADDR is the recipient; T is the thread id and is
                    # not an address, so it must never be used as a fallback.
                    "to":      _unescape(m.get("TOADDR") or m.get("TO") or ""),
                }
                for m in msgs[:limit]
            ]
        finally:
            await browser.close()

read_email(msg_id, folder=None) async

Read the full content of a single email.

Fetches the complete message including HTML body, sender details, and threading headers needed for replies.

Parameters:

Name Type Description Default
msg_id str

The Zoho message ID (id field from :meth:list_emails).

required

Returns:

Type Description
dict

A dict containing:

dict
  • id (str) — Zoho message ID.
dict
  • from (str) — Sender email address.
dict
  • reply_to (str) — Address to send replies to.
dict
  • to (str) — Recipient address.
dict
  • date (str) — Human-readable sent date.
dict
  • subject (str) — Message subject.
dict
  • message_id (str) — RFC 2822 Message-ID for threading.
dict
  • body (str) — Plain-text body (stripped from HTML).
dict
  • body_html (str) — Raw HTML body.
dict
  • attachments (list[dict]) — One entry per attachment with name, format, size_bytes, part_id, attachment_id, and inline. Empty list if none.

Raises:

Type Description
ZohoMailError

If authentication or the API call fails.

Example

email = asyncio.run(client.read_email("1782000221530004400")) print(email["body"])

Source code in zohomail/client.py
async def read_email(self, msg_id: str, folder: str | None = None) -> dict:
    """Read the full content of a single email.

    Fetches the complete message including HTML body, sender details,
    and threading headers needed for replies.

    Args:
        msg_id: The Zoho message ID (``id`` field from :meth:`list_emails`).

    Returns:
        A dict containing:

        - ``id`` (*str*) — Zoho message ID.
        - ``from`` (*str*) — Sender email address.
        - ``reply_to`` (*str*) — Address to send replies to.
        - ``to`` (*str*) — Recipient address.
        - ``date`` (*str*) — Human-readable sent date.
        - ``subject`` (*str*) — Message subject.
        - ``message_id`` (*str*) — RFC 2822 Message-ID for threading.
        - ``body`` (*str*) — Plain-text body (stripped from HTML).
        - ``body_html`` (*str*) — Raw HTML body.
        - ``attachments`` (*list[dict]*) — One entry per attachment with
            ``name``, ``format``, ``size_bytes``, ``part_id``,
            ``attachment_id``, and ``inline``. Empty list if none.

    Raises:
        ZohoMailError: If authentication or the API call fails.

    Example:
        >>> email = asyncio.run(client.read_email("1782000221530004400"))
        >>> print(email["body"])
    """
    async with async_playwright() as p:
        browser, page = await self._get_page(p)
        try:
            return await self._read_in_page(page, msg_id, folder)
        finally:
            await browser.close()

send

zohomail.smtp.send(from_addr, app_password, to, subject, body, *, region='eu', from_name='', cc=None, html=False, in_reply_to='', references='')

Send an email via Zoho SMTP.

Parameters:

Name Type Description Default
from_addr str

Sender address — must match the authenticated Zoho account.

required
app_password str

App-specific password generated in Zoho Security settings.

required
to list[str]

List of recipient email addresses.

required
subject str

Email subject line.

required
body str

Email body — plain text, or HTML if html=True.

required
region str

Zoho data-centre — "eu" (default) or "com".

'eu'
from_name str

Display name shown to recipients, e.g. "Ada Lovelace" renders as Ada Lovelace <ada@example.com>. Defaults to empty, which sends a bare address; most clients then invent a name from the local part, so hi@example.com shows up as "hi".

''
cc list[str] | None

Optional list of CC addresses.

None
html bool

If True, send body as HTML (with a plain-text fallback).

False
in_reply_to str

RFC 2822 Message-ID of the email being replied to. Sets In-Reply-To and References headers for threading.

''
references str

Override the References header. Defaults to in_reply_to when omitted.

''

Returns:

Type Description
dict

A dict with status, to, and subject keys::

{"status": "sent", "to": ["a@b.com"], "subject": "Hello"}

Raises:

Type Description
SMTPException

On connection or authentication failure.

Example

from zohomail.smtp import send send( ... from_addr="you@yourdomain.com", ... app_password="xxxx-xxxx", ... to=["friend@example.com"], ... subject="Hello", ... body="Hi there!", ... )

Source code in zohomail/smtp.py
def send(
    from_addr: str,
    app_password: str,
    to: list[str],
    subject: str,
    body: str,
    *,
    region: str = "eu",
    from_name: str = "",
    cc: list[str] | None = None,
    html: bool = False,
    in_reply_to: str = "",
    references: str = "",
) -> dict:
    """Send an email via Zoho SMTP.

    Args:
        from_addr: Sender address — must match the authenticated Zoho account.
        app_password: App-specific password generated in Zoho Security settings.
        to: List of recipient email addresses.
        subject: Email subject line.
        body: Email body — plain text, or HTML if ``html=True``.
        region: Zoho data-centre — ``"eu"`` (default) or ``"com"``.
        from_name: Display name shown to recipients, e.g. ``"Ada Lovelace"``
            renders as ``Ada Lovelace <ada@example.com>``. Defaults to empty,
            which sends a bare address; most clients then invent a name from
            the local part, so ``hi@example.com`` shows up as "hi".
        cc: Optional list of CC addresses.
        html: If ``True``, send ``body`` as HTML (with a plain-text fallback).
        in_reply_to: RFC 2822 ``Message-ID`` of the email being replied to.
            Sets ``In-Reply-To`` and ``References`` headers for threading.
        references: Override the ``References`` header. Defaults to
            ``in_reply_to`` when omitted.

    Returns:
        A dict with ``status``, ``to``, and ``subject`` keys::

            {"status": "sent", "to": ["a@b.com"], "subject": "Hello"}

    Raises:
        smtplib.SMTPException: On connection or authentication failure.

    Example:
        >>> from zohomail.smtp import send
        >>> send(
        ...     from_addr="you@yourdomain.com",
        ...     app_password="xxxx-xxxx",
        ...     to=["friend@example.com"],
        ...     subject="Hello",
        ...     body="Hi there!",
        ... )
    """
    host = f"smtp.zoho.{'eu' if region.lower() == 'eu' else 'com'}"
    msg = EmailMessage()
    msg["From"] = formataddr((from_name, from_addr)) if from_name else from_addr
    msg["To"] = ", ".join(to)
    if cc:
        msg["Cc"] = ", ".join(cc)
    msg["Subject"] = subject
    msg["Date"] = formatdate(localtime=True)
    msg["Message-ID"] = make_msgid()
    if in_reply_to:
        msg["In-Reply-To"] = in_reply_to
        msg["References"] = references or in_reply_to
    if html:
        msg.set_content("This message requires an HTML-capable client.")
        msg.add_alternative(body, subtype="html")
    else:
        msg.set_content(body)

    recipients = list(to) + list(cc or [])
    with smtplib.SMTP_SSL(host, 465, context=_ssl_ctx()) as s:
        s.login(from_addr, app_password)
        s.send_message(msg, from_addr=from_addr, to_addrs=recipients)

    return {"status": "sent", "to": recipients, "subject": subject}

Exceptions

zohomail.client.ZohoMailError

Bases: Exception

Base exception for all zohomail-free errors.

Source code in zohomail/client.py
class ZohoMailError(Exception):
    """Base exception for all zohomail-free errors."""

zohomail.client.SessionExpiredError

Bases: ZohoMailError

Raised when the Zoho session expires and re-authentication fails.

Source code in zohomail/client.py
class SessionExpiredError(ZohoMailError):
    """Raised when the Zoho session expires and re-authentication fails."""

Built by MelkonTech