如何编写合同到期提醒脚本

wen 实用脚本 30

本文目录导读:

如何编写合同到期提醒脚本

  1. 基础 Python 脚本(推荐)
  2. Excel 文件读取版本
  3. Windows 任务计划程序配置
  4. Linux Crontab 配置
  5. 微信/钉钉通知版本
  6. 配置文件 (config.json)
  7. 使用建议

我来帮你编写一个合同到期提醒脚本,这里提供几种常见实现方式:

基础 Python 脚本(推荐)

import datetime
import smtplib
from email.mime.text import MIMEText
import json
class ContractReminder:
    def __init__(self):
        # 合同数据
        self.contracts = [
            {
                "name": "供应商A合同",
                "expire_date": "2024-03-15",
                "party": "供应商A",
                "remind_days": [30, 15, 7, 3, 1]
            },
            {
                "name": "租赁合同",
                "expire_date": "2024-04-01",
                "party": "房东",
                "remind_days": [30, 7]
            }
        ]
        # 邮件配置
        self.email_config = {
            "smtp_server": "smtp.qq.com",
            "smtp_port": 587,
            "sender": "your_email@qq.com",
            "password": "your_password",
            "recipients": ["manager@company.com"]
        }
    def check_expiry(self):
        """检查合同到期情况"""
        today = datetime.date.today()
        reminders = []
        for contract in self.contracts:
            expire_date = datetime.datetime.strptime(
                contract["expire_date"], "%Y-%m-%d"
            ).date()
            days_until_expiry = (expire_date - today).days
            if days_until_expiry in contract["remind_days"]:
                reminders.append({
                    "name": contract["name"],
                    "party": contract["party"],
                    "days_left": days_until_expiry,
                    "expire_date": contract["expire_date"]
                })
            # 已过期合同提醒
            if days_until_expiry < 0 and abs(days_until_expiry) <= 7:
                reminders.append({
                    "name": contract["name"],
                    "party": contract["party"],
                    "days_overdue": abs(days_until_expiry),
                    "expire_date": contract["expire_date"],
                    "overdue": True
                })
        return reminders
    def send_email(self, reminders):
        """发送邮件提醒"""
        if not reminders:
            return
        # 构建邮件内容
        message = "合同到期提醒\n\n"
        message += f"检查时间:{datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}\n"
        message += "=" * 40 + "\n\n"
        for item in reminders:
            if item.get("overdue"):
                message += f"⚠️ 已过期合同:{item['name']}\n"
                message += f"   合同方:{item['party']}\n"
                message += f"   已过期:{item['days_overdue']}天\n"
                message += f"   到期日:{item['expire_date']}\n\n"
            else:
                message += f"📅 即将到期合同:{item['name']}\n"
                message += f"   合同方:{item['party']}\n"
                message += f"   剩余:{item['days_left']}天\n"
                message += f"   到期日:{item['expire_date']}\n\n"
        # 发送邮件
        msg = MIMEText(message, 'plain', 'utf-8')
        msg['Subject'] = f"合同到期提醒 ({len(reminders)}条)"
        msg['From'] = self.email_config['sender'] 
        msg['To'] = ';'.join(self.email_config['recipients'])
        try:
            server = smtplib.SMTP(
                self.email_config['smtp_server'], 
                self.email_config['smtp_port']
            )
            server.starttls()
            server.login(
                self.email_config['sender'], 
                self.email_config['password']
            )
            server.send_message(msg)
            server.quit()
            print(f"✅ 邮件发送成功,共{len(reminders)}条提醒")
        except Exception as e:
            print(f"❌ 邮件发送失败: {e}")
# 使用示例
if __name__ == "__main__":
    reminder = ContractReminder()
    reminders = reminder.check_expiry()
    if reminders:
        print(f"发现 {len(reminders)} 条需要提醒的合同")
        reminder.send_email(reminders)
    else:
        print("✅ 没有即将到期的合同")

Excel 文件读取版本

import pandas as pd
from datetime import datetime, date
import warnings
warnings.filterwarnings('ignore')
class ExcelContractReminder:
    def __init__(self, excel_path='contracts.xlsx'):
        self.excel_path = excel_path
        self.df = pd.read_excel(excel_path)
    def process_contracts(self):
        """处理合同到期提醒"""
        today = date.today()
        # 计算剩余天数
        self.df['到期日期'] = pd.to_datetime(self.df['到期日期']).dt.date
        self.df['剩余天数'] = (self.df['到期日期'] - today).dt.days
        # 筛选需要提醒的合同
        expire_soon = self.df[
            (self.df['剩余天数'] > 0) & 
            (self.df['剩余天数'] <= 30)
        ].sort_values('剩余天数')
        expired = self.df[self.df['剩余天数'] < 0].sort_values('剩余天数', ascending=False)
        return expire_soon, expired
    def print_reminder(self):
        """打印提醒信息"""
        expire_soon, expired = self.process_contracts()
        print("=" * 60)
        print(f"合同到期检查报告")
        print(f"检查日期:{date.today()}")
        print("=" * 60)
        if not expire_soon.empty:
            print(f"\n📅 即将到期合同 ({len(expire_soon)}条):")
            print("-" * 60)
            for _, row in expire_soon.iterrows():
                print(f"合同:{row['合同名称']}")
                print(f"合同方:{row['合同方']}")
                print(f"到期日:{row['到期日期']}")
                print(f"剩余:{row['剩余天数']}天")
                print(f"金额:{row.get('金额', 'N/A')}")
                print("-" * 60)
        if not expired.empty:
            print(f"\n⚠️ 已过期合同 ({len(expired)}条):")
            print("-" * 60)
            for _, row in expired.iterrows():
                print(f"合同:{row['合同名称']}")
                print(f"合同方:{row['合同方']}")
                print(f"过期:{abs(row['剩余天数'])}天")
                print(f"金额:{row.get('金额', 'N/A')}")
                print("-" * 60)
# 创建示例 Excel 文件
def create_sample_excel():
    data = {
        '合同名称': ['租赁合同', '供应合同', '服务合同', '采购合同'],
        '合同方': ['房东A', '供应商B', '服务商C', '供应商D'],
        '到期日期': ['2024-03-15', '2024-04-01', '2024-02-28', '2024-03-20'],
        '金额': [50000, 200000, 80000, 150000],
        '负责人': ['张三', '李四', '王五', '赵六']
    }
    df = pd.DataFrame(data)
    df.to_excel('contracts.xlsx', index=False)
    print("示例 Excel 文件已创建")
if __name__ == "__main__":
    # 创建示例文件
    create_sample_excel()
    # 运行提醒
    reminder = ExcelContractReminder('contracts.xlsx')
    reminder.print_reminder()

Windows 任务计划程序配置

创建 reminder_script.bat 文件:

@echo off
cd /d %~dp0
python contract_reminder.py
pause

配置 Windows 任务计划:

  1. 打开"任务计划程序"
  2. 创建基本任务
  3. 设置触发器(每天上午9点)
  4. 操作:启动程序 → 选择 bat 文件

Linux Crontab 配置

# 编辑 crontab
crontab -e
# 每天早上9点运行
0 9 * * * cd /path/to/script && python3 contract_reminder.py
# 或者每小时检查一次
0 * * * * cd /path/to/script && python3 contract_reminder.py

微信/钉钉通知版本

import requests
import json
def send_wechat_work_robot(webhook_url, content):
    """发送企业微信机器人消息"""
    data = {
        "msgtype": "text",
        "text": {
            "content": content,
            "mentioned_list": ["@all"]  # 提醒所有人
        }
    }
    response = requests.post(
        webhook_url, 
        data=json.dumps(data),
        headers={"Content-Type": "application/json"}
    )
    return response.json()
def send_dingtalk_robot(webhook_url, content):
    """发送钉钉机器人消息"""
    data = {
        "msgtype": "text",
        "text": {
            "content": content
        },
        "at": {
            "isAtAll": True
        }
    }
    response = requests.post(
        webhook_url,
        data=json.dumps(data),
        headers={"Content-Type": "application/json"}
    )
    return response.json()

配置文件 (config.json)

{
    "contracts_file": "contracts.xlsx",
    "remind_days": [30, 15, 7, 3, 1],
    "notification": {
        "email": {
            "enabled": true,
            "smtp_server": "smtp.qq.com",
            "smtp_port": 587,
            "sender": "your_email@qq.com",
            "recipients": ["manager@company.com"]
        },
        "wechat": {
            "enabled": false,
            "webhook_url": ""
        },
        "dingtalk": {
            "enabled": false,
            "webhook_url": ""
        }
    }
}

使用建议

  1. 数据源选择:企业可用数据库,个人可用 Excel
  2. 提醒频率:重要合同建议提前30天、15天、7天、1天提醒
  3. 多渠道通知:邮件、微信、短信等多种方式
  4. 记录日志:记录每次检查结果,便于追踪
  5. 自动更新:可集成到 CI/CD 或定时任务

需要根据你的具体需求,选择合适的版本进行修改和扩展。

抱歉,评论功能暂时关闭!