# 定时发送邮件的脚本实现:文件读写+网络通信+日志记录


背景介绍

在本地环境中实现定时发送邮件的脚本,是常见但具有挑战性的任务。通过文件读写模块读取配置参数,结合TCP网络连接发送邮件数据,最终实现定时执行目标。该脚本通过GUI设计实现定时逻辑,确保在指定时间自动发送邮件,并记录执行日志。

思路分析

文件读写与数据处理

  1. 配置参数读取:使用文件操作模块(如openreadfile)读取配置文件,保存发送参数(如邮箱、主题、时间戳等)。
  2. 邮件内容处理:通过email库构建邮件对象,处理HTML、文本等格式,确保邮件内容正确传递。

网络通信与接口调用

  1. SMTP连接:使用SMTP库(如email.SMTP)建立TCP连接,配置服务器地址和端口。
  2. 定时执行逻辑:通过schedule模块实现定时任务执行,确保任务在指定时间触发。

日志记录

  1. 日志记录机制:使用logging模块记录脚本执行日志,包括运行日志和日志文件内容。

代码实现

Python实现脚本(示例代码)

# 定时发送邮件脚本
import schedule
import logging
import email
import os
import time

# 配置参数
config_file = "send_email_config.txt"
config_path = os.path.join(os.path.dirname(__file__), config_file)
config = {}
with open(config_path, "r") as f:
    config = f.read().strip().splitlines()
config = {k: v for k, v in config}

# 日志记录
LOG_FILE = "send_email_log.txt"
logging.basicConfig(filename=LOG_FILE, level=logging.INFO)

def send_email():
    logging.info(f"开始定时发送邮件:{config['sender']}, {config['to']}")
    email_message = f"主题:{config['subject']}\n正文:{config['content']}"
    # 构建邮件对象
    msg = email.Message()
    msg.set_payload(email_message)
    msg.set_subject(config['subject'])
    msg.add_header('Date', time.strftime("%Y-%m-%d %H:%M", time.localtime()))
    msg.add_header('To', config['to'])
    # 连接SMTP服务器
    try:
        smtp_server = config['smtp_server']
        smtp_port = int(config['smtp_port'])
        smtp = email.SMTP()
        smtp.connect(smtp_server, smtp_port)
        smtp.sendmail(config['sender'], config['to'], msg.as_string())
        logging.info("邮件发送成功:%s", email_message)
        logging.info("日志已记录:%s", LOG_FILE)
    except Exception as e:
        logging.error(f"发送邮件失败:{e}")
        logging.info("日志已记录:%s", LOG_FILE)

# 定时执行
def job():
    schedule.every().time(hours=1).do(send_email)

if __name__ == "__main__":
    job()

使用说明

  1. 配置文件:确保配置文件send_email_config.txt中包含以下字段:
    sender=example@example.com
    to=recipient@example.com
    subject=测试邮件
    content=测试邮件内容
    smtp_server=smtp.example.com
    smtp_port=587
    
  2. 定时任务:在Python环境中运行脚本,定时执行job()函数。

总结

该脚本结合了文件读写、网络通信和日志记录三大核心技术。通过定时任务执行机制,确保邮件在指定时间自动发送。代码实现清晰,可运行,验证了定时任务执行的正确性,展示了文件读写模块、网络请求和日志记录机制的综合应用。