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でリモートメールボックスを構築した後、ウェブインターフェースがメールボックスを読み取れない問題

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}")
読み込み中...
文章は、創作者によって署名され、ブロックチェーンに安全に保存されています。