You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python自定义提醒函数改造为可多选调用的功能

多选提醒功能修正方案

原有代码的核心问题

  • 缺少必要模块导入:使用smtplib、EmailMessage前没有对应导入语句
  • 冗余空类reminder定义,后续函数缩进逻辑混乱,未脱离类作用域
  • 配置字典options存在语法错误:选项A对应的列表多了多余逗号,函数引用位置错误
  • 重复定义两次if __name__ == '__main__'逻辑,且第二个测试块错误调用了email_alert而非对应send_sms_via_email函数
  • 调用函数时未传递对应参数:email_alert、send_sms_via_email需要3个入参,snail_mail需要1个入参,原有逻辑直接执行action()会报参数数量错误

修正后可运行代码

import smtplib
from email.message import EmailMessage

def email_alert(subject, body, to):
    msg = EmailMessage()
    msg.set_content(body)
    msg["subject"] = subject
    msg["to"] = to

    user = "#######@.com"
    msg["from"] = user
    password = "########"

    # 替换为对应邮箱的SMTP服务器地址,比如QQ邮箱为smtp.qq.com,163邮箱为smtp.163.com
    server = smtplib.SMTP_SSL("smtp.你的邮箱域名.com", 465)
    server.login(user, password)
    server.send_message(msg)
    server.quit()

def send_sms_via_email(subject, body, to):
    msg = EmailMessage()
    msg.set_content(body)
    msg["subject"] = subject
    msg["to"] = to

    user = "##########@.com"
    msg["from"] = user
    password = "##########"

    # 替换为对应邮箱的SMTP服务器地址
    server = smtplib.SMTP_SSL("smtp.你的邮箱域名.com", 465)
    server.login(user, password)
    server.send_message(msg)
    server.quit()

def snail_mail(s):
    print(f"请发送邮件至 ########@.com 申请平信提醒:{s}")

def invalid_selection():
    print("选择无效,请重试")

if __name__ == '__main__':
    # 预先配置提醒通用参数,可根据需求修改
    reminder_subject = "房租支付提醒"
    reminder_body = "您好,温馨提醒您房租已到期,请在月底前完成支付,否则将产生50美元滞纳金。感谢配合,管理处。"
    email_receiver = "#########@.com"
    sms_receiver = "######@.net"
    snail_mail_msg = "房租到期通知"

    options = {
        "A": ["邮件提醒", email_alert],
        "B": ["短信提醒", send_sms_via_email],
        "C": ["平信提醒", snail_mail]
    }

    print("请选择提醒方式:")
    for option in options:
        print(f"{option}) {options[option][0]}")

    choice = input("请输入对应选项字母:").strip().upper()
    val = options.get(choice)
    if val is not None:
        action = val[1]
        if choice in ("A", "B"):
            receiver = email_receiver if choice == "A" else sms_receiver
            action(reminder_subject, reminder_body, receiver)
            print("提醒发送成功")
        elif choice == "C":
            action(snail_mail_msg)
    else:
        invalid_selection()

额外优化建议

  • 可以把两个发邮件函数的公共逻辑抽成通用工具函数,减少重复代码
  • 敏感的邮箱账号、密码不要硬编码在代码里,可以放到环境变量或者配置文件中读取
  • 可以增加异常捕获逻辑,处理邮件发送失败的情况

内容的提问来源于stack exchange,提问作者Luis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 13:45:06