mail-chat / app.py
neruf's picture
Upload folder using huggingface_hub
9cc440c verified
Raw History Blame Contribute Delete
4.42 kB
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()