File size: 4,423 Bytes
9cc440c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import gradio as gr
import smtplib
import imaplib
import email
from email.mime.text import MIMEText
import os

# ==========================================
# 設定(Hugging Face Spaces の Secrets から取得)
# ==========================================
MY_EMAIL = os.environ.get("MY_EMAIL", "")
MY_PASSWORD = os.environ.get("MY_PASSWORD", "")
PEER_EMAIL = os.environ.get("PEER_EMAIL", "")
SMTP_SERVER = os.environ.get("SMTP_SERVER", "smtp.gmail.com")
SMTP_PORT = int(os.environ.get("SMTP_PORT", "587"))
IMAP_SERVER = os.environ.get("IMAP_SERVER", "imap.gmail.com")


def send_email(text: str) -> tuple[bool, str]:
    """SMTPでメールを送信する"""
    try:
        msg = MIMEText(text, "plain", "utf-8")
        msg["Subject"] = "Chat Message"
        msg["From"] = MY_EMAIL
        msg["To"] = PEER_EMAIL

        with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
            server.starttls()
            server.login(MY_EMAIL, MY_PASSWORD)
            server.send_message(msg)
        return True, ""
    except Exception as e:
        return False, str(e)


def fetch_new_emails() -> list[str]:
    """IMAPで相手からの未読メールを取得する"""
    messages: list[str] = []
    try:
        with imaplib.IMAP4_SSL(IMAP_SERVER) as mail:
            mail.login(MY_EMAIL, MY_PASSWORD)
            mail.select("inbox")

            status, data = mail.search(None, f'(UNSEEN FROM "{PEER_EMAIL}")')
            if status != "OK" or not data[0]:
                return messages

            for num in data[0].split():
                typ, msg_data = mail.fetch(num, "(RFC822)")
                raw = msg_data[0][1]
                msg = email.message_from_bytes(raw)

                body = ""
                if msg.is_multipart():
                    for part in msg.walk():
                        if part.get_content_type() == "text/plain":
                            payload = part.get_payload(decode=True)
                            if payload:
                                body = payload.decode("utf-8", errors="ignore")
                            break
                else:
                    payload = msg.get_payload(decode=True)
                    if payload:
                        body = payload.decode("utf-8", errors="ignore")

                if body.strip():
                    messages.append(body.strip())
    except Exception:
        pass
    return messages


def send_message(message: str, history: list[dict]) -> tuple[str, list[dict]]:
    """メッセージ送信"""
    if not message.strip():
        return "", history

    if not all([MY_EMAIL, MY_PASSWORD, PEER_EMAIL]):
        history.append({"role": "assistant", "content": "⚠️ 環境変数 MY_EMAIL, MY_PASSWORD, PEER_EMAIL を設定してください。"})
        return "", history

    ok, err = send_email(message.strip())
    if ok:
        history.append({"role": "user", "content": message.strip()})
    else:
        history.append({"role": "assistant", "content": f"❌ 送信エラー: {err}"})
    return "", history


def check_mail(history: list[dict]) -> list[dict]:
    """新着メール確認"""
    if not all([MY_EMAIL, MY_PASSWORD, PEER_EMAIL]):
        return history

    new_msgs = fetch_new_emails()
    for m in new_msgs:
        history.append({"role": "assistant", "content": m})
    return history


# ==========================================
# Gradio UI
# ==========================================
with gr.Blocks(
    title="MailChat",
    theme=gr.themes.Soft(
        primary_hue="blue",
        font=["Noto Sans JP", "sans-serif"],
    ),
    css="""
    .gradio-container { max-width: 600px !important; margin: auto; }
    """,
) as demo:
    gr.Markdown("# 💬 MailChat\n裏側はメールで動くチャットアプリ")

    chatbot = gr.Chatbot(type="messages", height=400, label="チャット")

    with gr.Row():
        msg_input = gr.Textbox(
            placeholder="メッセージを入力...",
            show_label=False,
            scale=5,
            container=False,
        )
        send_btn = gr.Button("送信", scale=1, variant="primary")
        refresh_btn = gr.Button("🔄", scale=0, min_width=50)

    send_btn.click(send_message, [msg_input, chatbot], [msg_input, chatbot])
    msg_input.submit(send_message, [msg_input, chatbot], [msg_input, chatbot])
    refresh_btn.click(check_mail, [chatbot], [chatbot])

demo.launch()