email.iterators:迭代器

原始碼: Lib/email/iterators.py


使用 Message.walk 方法,遍歷訊息物件樹非常容易。email.iterators 模組提供了一些有用的、更高階的訊息物件樹迭代方式。

email.iterators.body_line_iterator(msg, decode=False)

這將迭代 *msg* 的所有子部分中的所有有效負載,逐行返回字串有效負載。它跳過所有子部分的標頭,並跳過任何有效負載不是 Python 字串的子部分。這有點類似於使用 readline() 從檔案中讀取訊息的平面文字表示,並跳過所有中間的標頭。

可選的 *decode* 將傳遞給 Message.get_payload

email.iterators.typed_subpart_iterator(msg, maintype='text', subtype=None)

這將迭代 *msg* 的所有子部分,僅返回那些與 *maintype* 和 *subtype* 指定的 MIME 型別匹配的子部分。

請注意,*subtype* 是可選的;如果省略,則子部分 MIME 型別匹配僅使用主型別完成。*maintype* 也是可選的;它預設為 text

因此,預設情況下 typed_subpart_iterator() 返回每個 MIME 型別為 text/* 的子部分。

以下函式已新增為有用的除錯工具。它應被視為包的受支援的公共介面的一部分。

email.iterators._structure(msg, fp=None, level=0, include_default=False)

列印訊息物件結構的內容型別的縮排表示。例如

>>> msg = email.message_from_file(somefile)
>>> _structure(msg)
multipart/mixed
    text/plain
    text/plain
    multipart/digest
        message/rfc822
            text/plain
        message/rfc822
            text/plain
        message/rfc822
            text/plain
        message/rfc822
            text/plain
        message/rfc822
            text/plain
    text/plain

可選的 *fp* 是一個用於列印輸出的檔案類物件。它必須適用於 Python 的 print() 函式。*level* 在內部使用。如果 *include_default* 為 true,則還會列印預設型別。