banner
andrewji8

Being towards death

Heed not to the tree-rustling and leaf-lashing rain, Why not stroll along, whistle and sing under its rein. Lighter and better suited than horses are straw sandals and a bamboo staff, Who's afraid? A palm-leaf plaited cape provides enough to misty weather in life sustain. A thorny spring breeze sobers up the spirit, I feel a slight chill, The setting sun over the mountain offers greetings still. Looking back over the bleak passage survived, The return in time Shall not be affected by windswept rain or shine.
telegram
twitter
github

解決serv00搭建好遠程郵箱後,web界面無法讀取郵箱問題

import imaplib
import email
from email.header import decode_header

# 配置信息
IMAP_SERVER = "mailx.serv00.com " # mailx.serv00.com  x表示你伺服器的數字
EMAIL = "[email protected]" # 你的郵箱地址
PASSWORD = "your-password" # 你的郵箱密碼

try:
    # 連接到 IMAP 伺服器
    print(f"正在連接到 {IMAP_SERVER}...")
    mail = imaplib.IMAP4_SSL(IMAP_SERVER)
    
    # 登錄
    print("正在登錄...")
    mail.login(EMAIL, PASSWORD)
    print("登錄成功!")

    # 選擇收件箱
    mail.select("inbox")
    print("已選擇收件箱。")

    # 搜索郵件(例如:所有郵件)
    status, messages = mail.search(None, "ALL")
    if status != "OK":
        print("未找到郵件。")
        exit()

    # 獲取郵件 ID 列表
    email_ids = messages[0].split()
    print(f"找到 {len(email_ids)} 封郵件。")

    # 遍歷每封郵件
    for i, email_id in enumerate(email_ids[-5:], start=1):  # 只讀取最後 5 封郵件
        print(f"\n正在讀取第 {i} 封郵件...")
        
        # 獲取郵件內容
        status, msg_data = mail.fetch(email_id, "(RFC822)")
        if status != "OK":
            print("無法讀取郵件內容。")
            continue

        # 解析郵件內容
        for response_part in msg_data:
            if isinstance(response_part, tuple):
                msg = email.message_from_bytes(response_part[1])  # 解析郵件
                
                # 提取郵件主題
                subject, encoding = decode_header(msg["Subject"])[0]
                if isinstance(subject, bytes):
                    subject = subject.decode(encoding or "utf-8")
                print(f"主題: {subject}")

                # 提取發件人
                from_ = msg.get("From")
                print(f"發件人: {from_}")

                # 提取郵件正文
                if msg.is_multipart():
                    for part in msg.walk():
                        content_type = part.get_content_type()
                        content_disposition = str(part.get("Content-Disposition"))
                        
                        # 提取純文本內容
                        if content_type == "text/plain" and "attachment" not in content_disposition:
                            body = part.get_payload(decode=True).decode()
                            print(f"正文:\n{body}")
                else:
                    body = msg.get_payload(decode=True).decode()
                    print(f"正文:\n{body}")

except imaplib.IMAP4.error as e:
    print(f"IMAP 錯誤: {e}")
except Exception as e:
    print(f"其他錯誤: {e}")
finally:
    # 關閉連接
    if 'mail' in locals():
        mail.logout()
        print("已斷開連接。")

代碼解析#

(1) 連接和登錄
使用 imaplib.IMAP4_SSL 連接到 IMAP 伺服器。
調用 login 方法進行身份驗證。
(2) 選擇郵箱文件夾
使用 select ("inbox") 選擇收件箱。您也可以選擇其他文件夾,例如 "Sent" 或 "Drafts"。
(3) 搜索郵件
使用 search (None, "ALL") 查找所有郵件。
返回的 messages 是一個包含郵件 ID 的字節字符串列表。
(4) 獲取郵件內容
使用 fetch (email_id, "(RFC822)") 獲取指定郵件的完整內容。
RFC822 表示返回完整的郵件數據。
(5) 解析郵件內容
使用 email.message_from_bytes 將郵件數據解析為 MIME 對象。
使用 decode_header 解碼郵件主題和發件人信息。
如果郵件是多部分(multipart),遍歷每個部分以提取正文或附件。

處理附件#

如果郵件包含附件,可以通過檢查 Content-Disposition 來提取附件。以下是處理附件的代碼片段:

代碼解析#

1. 連接和登錄#

  • 使用 imaplib.IMAP4_SSL 連接到 IMAP 伺服器。
  • 調用 login 方法進行身份驗證。

2. 選擇郵箱文件夾#

  • 使用 select("inbox") 選擇收件箱。您也可以選擇其他文件夾,例如 "Sent" 或 "Drafts"。

3. 搜索郵件#

  • 使用 search(None, "ALL") 查找所有郵件。
  • 返回的 messages 是一個包含郵件 ID 的字節字符串列表。

4. 獲取郵件內容#

  • 使用 fetch(email_id, "(RFC822)") 獲取指定郵件的完整內容。
  • RFC822 表示返回完整的郵件數據。

5. 解析郵件內容#

  • 使用 email.message_from_bytes 將郵件數據解析為 MIME 對象。
  • 使用 decode_header 解碼郵件主題和發件人信息。
  • 如果郵件是多部分(multipart),遍歷每個部分以提取正文或附件。

6. 處理附件#

如果郵件包含附件,可以通過檢查 Content-Disposition 來提取附件。以下是處理附件的代碼片段:

if "attachment" in content_disposition:
    filename = part.get_filename()
    if filename:
        filepath = f"./attachments/{filename}"
        with open(filepath, "wb") as f:
            f.write(part.get_payload(decode=True))
        print(f"附件已保存: {filepath}")
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。