python 自动把mysql备份文件发送邮箱

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import os
import time
import sched
 
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
 
# 第一个参数确定任务的时间,返回从某个特定的时间到现在经历的秒数
# 第二个参数以某种人为的方式衡量时间
schedule = sched.scheduler(time.time, time.sleep)
 
 
def backupsDB():
    cmdString = 'E:/BCSoft/mysql-8.0.15-winx64/bin/mysqldump -hlocalhost -uroot -p123456 kzxtms >  c:/mysqlbackup/kzxtms_backup.sql'
    os.system(cmdString)
 
 
def sendMail():
    _user = "xxxxxx0@xxx.com"  # 发送者的邮箱
    _pwd = "xxxxx"  # 发送者的密码  网易邮箱必须采用授权码 而不是密码
    _to = "xxxxxx@xxxx.com"  # 接收者的邮箱
 
    # 如名字所示Multipart就是分多个部分
    msg = MIMEMultipart()
    msg["Subject"] = "石黄高速智能灌溉系统数据库备份"
    msg["From"] = _user
    msg["To"] = _to
 
    # ---这是文字部分---
    part = MIMEText("石黄高速智能灌溉系统数据库备份")
    msg.attach(part)
 
    # ---这是附件部分---
    # 类型附件
    part = MIMEApplication(
        open('c:/mysqlbackup/kzxtms_backup.sql', 'rb').read())
    part.add_header('Content-Disposition', 'attachment',
                    filename="kzxtms_backup.sql")
    msg.attach(part)
  //  s = smtplib.SMTP("smtp.163.com", timeout=30# 连接smtp邮件服务器,端口默认是25    s.login(_user, _pwd)  # 登陆服务器
    s.sendmail(_user, _to, msg.as_string())  # 发送邮件
    s.close()
 
 
def perform_command(cmd, inc):
    # 安排inc秒后再次运行自己,即周期运行
    schedule.enter(inc, 0, perform_command, (cmd, inc))
    os.system(cmd)
    backupsDB()
    sendMail()
 
 
def timming_exe(cmd, inc=60):
    # enter用来安排某事件的发生时间,从现在起第n秒开始启动
    schedule.enter(inc, 0, perform_command, (cmd, inc))
    # 持续运行,直到计划时间队列变成空为止
    schedule.run()
 
 
if __name__ == '__main__':
    print("show time after 10 seconds:")
    timming_exe("echo %time%",86400) # 每间隔86400秒备份发送邮件 86400秒=1天
    s = smtplib.SMTP_SSL("smtp.163.com", 465)  # 连接smtp邮件服务器,端口默认是25

  

posted @   慢慢摸索  阅读(270)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示