发邮件|发封邮件|发送邮件|发一封邮件|帮我发邮件|帮我发封邮件|帮我发送邮件

import os
import re
import json
import requests
import subprocess
from datetime import datetime

# ========================================================
# 1. 定位 knowledge 目录及各文件路径
# ========================================================
base_dir = os.path.dirname(os.path.abspath(__file__)) if "__file__" in globals() else os.getcwd()
knowledge_dir = os.path.join(base_dir, "knowledge") if not os.path.basename(base_dir).lower() == "knowledge" else base_dir

key_file = os.path.join(knowledge_dir, "key.txt")
template_file = os.path.join(knowledge_dir, "mail1355.txt")
mail_txt_file = os.path.join(knowledge_dir, "mail.txt")
mail_exe_file = os.path.join(knowledge_dir, "mail.exe")

# ========================================================
# 2. 动态读取 key.txt（不写死 Key / 接口 / 模型）
# ========================================================
if not os.path.isfile(key_file):
    result = f"执行失败：找不到 Key 配置文件：{key_file}"
elif not os.path.isfile(template_file):
    result = f"执行失败：找不到模板文件：{template_file}"
else:
    with open(key_file, "r", encoding="utf-8", errors="ignore") as f:
        key_lines = [line.strip() for line in f.read().splitlines() if line.strip()]

    if not key_lines:
        result = "执行失败：knowledge/key.txt 内容为空"
    else:
        # 提取 API Key
        api_key = key_lines[0]
        if api_key.lower().startswith("api_key="):
            api_key = api_key.split("=", 1)[1].strip()

        # 提取 API URL
        api_url = "https://api.openai.com/v1/chat/completions"
        for line in key_lines[1:]:
            if line.startswith("http://") or line.startswith("https://"):
                url = line.rstrip("/")
                if url.endswith("/v1/chat/completions"):
                    api_url = url
                elif url.endswith("/v1"):
                    api_url = url + "/chat/completions"
                else:
                    api_url = url + "/v1/chat/completions"
                break

        # 提取模型名称
        model_name = "gpt-4o"
        for line in key_lines[1:]:
            if line.lower().startswith("model="):
                model_name = line.split("=", 1)[1].strip()
                break

        # ========================================================
        # 3. 读取模板 mail1355.txt（仅作提取，不破坏原文件）
        # ========================================================
        with open(template_file, "r", encoding="utf-8", errors="ignore") as f:
            template_text = f.read()

        # 解析模板已有配置块
        server_section = re.search(r"(\[邮箱服务器\][\s\S]*?)(?=\n\s*\[|\Z)", template_text)
        user_section = re.search(r"(\[用户信息\][\s\S]*?)(?=\n\s*\[|\Z)", template_text)
        roster_section = re.search(r"\[发送名单\]([\s\S]*?)(?=\n\s*\[|\Z)", template_text)

        # 提取收件人名单
        contacts = {}
        if roster_section:
            for line in roster_section.group(1).splitlines():
                if "=" in line:
                    name, email = line.split("=", 1)
                    contacts[name.strip()] = email.strip()

        contact_names = "、".join(contacts.keys()) if contacts else "无"

        # ========================================================
        # 4. 连接 ChatGPT：提取收件人并润色邮件主题和正文
        # ========================================================
        prompt = f"""
你是一个专业的中文邮件秘书助手。
用户当前指令为："{query}"

已知通讯录联系人：{contact_names}

请完成以下任务：
1. 分析用户要发给谁：如果指令中提到了通讯录中的某个名字，提取该名字；如果没提或无法确定，设为 null。
2. 根据用户的意图，提炼一个简洁规范、商务得体的“邮件主题”。
3. 将用户要传达的事项进行润色，撰写为排版整洁、用词得体、格式规范的正式邮件正文（包含礼貌称呼、详细事由、致敬语）。

严格以 JSON 格式输出，不要输出任何多余解释或 Markdown 格式以外的内容，字段如下：
{{
    "recipient": "收件人姓名或null",
    "subject": "润色后的邮件主题",
    "content": "润色后的邮件完整正文"
}}
"""

        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_key}"
        }

        payload = {
            "model": model_name,
            "messages": [
                {"role": "system", "content": "你是一位优秀的公文与电子邮件撰写专家，严格按 JSON 格式输出。"},
                {"role": "user", "content": prompt}
            ],
            "temperature": 0.3
        }

        try:
            resp = requests.post(api_url, headers=headers, json=payload, timeout=60)
            resp.raise_for_status()
            res_content = resp.json()["choices"][0]["message"]["content"].strip()

            # 清洗代码块标记
            if "```json" in res_content:
                res_content = res_content.split("```json")[1].split("```")[0].strip()
            elif "```" in res_content:
                res_content = res_content.split("```")[1].split("```")[0].strip()

            mail_info = json.loads(res_content)
            new_subject = mail_info.get("subject", "通知").strip()
            new_body = mail_info.get("content", "").strip()
            chosen_recipient = mail_info.get("recipient")

        except Exception as gpt_err:
            result = f"调用 ChatGPT 润色邮件失败：{gpt_err}"
        else:
            # ========================================================
            # 5. 按照 mail1355.txt 模板格式生成临时 mail.txt
            # ========================================================
            final_roster_lines = []
            if chosen_recipient and chosen_recipient in contacts:
                final_roster_lines.append(f"{chosen_recipient}={contacts[chosen_recipient]}")
            elif contacts:
                for name, email in contacts.items():
                    final_roster_lines.append(f"{name}={email}")
            else:
                final_roster_lines.append("默认收件人=example@domain.com")

            server_part = server_section.group(1).strip() if server_section else "[邮箱服务器]\n服务器=smtp.163.com\n端口=465\nSSL=是"
            user_part = user_section.group(1).strip() if user_section else "[用户信息]\n用户名=\n密码="

            mail_txt_content = f"""{server_part}


{user_part}


[邮件设置]
主题={new_subject}

内容=
{new_body}


[发送名单]
""" + "\n".join(final_roster_lines) + "\n"

            # 写入临时 mail.txt
            with open(mail_txt_file, "w", encoding="utf-8") as f:
                f.write(mail_txt_content)

            # ========================================================
            # 6. 运行 mail.exe 并发送邮件
            # ========================================================
            if not os.path.isfile(mail_exe_file):
                result = f"执行失败：在 {knowledge_dir} 目录下找不到 mail.exe"
            else:
                try:
                    # 在 knowledge 目录下启动 mail.exe
                    exe_run = subprocess.run(
                        [mail_exe_file],
                        cwd=knowledge_dir,
                        capture_output=True,
                        text=True,
                        timeout=60,
                        shell=False
                    )
                    output_log = (exe_run.stdout or "") + (exe_run.stderr or "")

                    result = f"【邮件发送完成】\n收件人：{', '.join(final_roster_lines)}\n主题：{new_subject}\n\n【邮件正文】：\n{new_body}\n\n【程序运行输出】：\n{output_log.strip()}"

                except Exception as exe_err:
                    result = f"执行 mail.exe 发送失败：{exe_err}"

                finally:
                    # ====================================================
                    # 7. 发送完毕后删除生成的临时 mail.txt（保留模板 mail1355.txt）
                    # ====================================================
                    if os.path.isfile(mail_txt_file):
                        try:
                            os.remove(mail_txt_file)
                        except Exception:
                            pass
