实用工具脚本制作
用python绿色版制作windows共享目录工具
免费电视APP神器-TVbox的安装及使用
python库email实现数据库自动备份
Windows技巧-设置右键快捷菜单
GitBash中文设置
本文档使用 MrDoc 发布
-
+
up
down
首页
python库email实现数据库自动备份
为了实现笔记网站的数据备份,使用了zmail进行定期备份。 主要为 ## 逻辑 本文示例,需要备份的是笔记数据库和对应的media目录下的图片文件。 ```mermaid graph LR A1[(数据库目录)] --压缩--> B(tar.gz文件) ==zmail发送==> 126邮箱 A2[/media目录/] --压缩--> B ``` ## 脚本定期执行  > w注意python路径,可能会有依赖包为安装,可以先测试好。 ## !废话不多说了,直接上效果图  ## !又废话了,直接上代码 ## 脚本及配置文件 ### config.conf ```shell [basic] server = smtp.qq.com port = 25 inbox = 1623470@qq.com inbox_auth_code = xxxxxxxxxxxxxx addresser = huQ #outbox = aaa1@qq.com,aaa2@qq.com outbox = test@126.com #addressee = aaa1,aaa2 addressee = hu26 theme = mrdoc备份 [content] body = content.htm format = plain back_path = /www/wwwroot/mrdocWB attachment1 = /path/to/file ``` ### send_email_cmdConfig.py ```python # coding=UTF-8 import datetime import email.mime.multipart import email.mime.text import os, sys import random import smtplib, zmail import time from email.header import Header # 处理邮件主题 from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import formataddr, parseaddr # 用于构造特定格式的收发邮件地址 import prettytable as pt now_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y%m%d-%H%M%S') #print(now_time) #now_path = os.path.abspath(os.curdir) now_path = os.path.split(os.path.abspath(__file__))[0] print(now_path) def print_tool_info(): tb = pt.PrettyTable() tb.field_names = ['名称', '邮件批量定制发送工具'] tb.add_row(['更新时间', '2022-10-26']) tb.add_row(['版本号', 'v1.1']) print(tb) def __format_addr(s): name, addr = parseaddr(s) return formataddr((Header(name, 'utf-8').encode(), addr)) def load_info(): from configparser import ConfigParser filepath = '' if filepath: configpath = filepath else: fileA = 'config.conf' if os.name == 'posix' else 'config.ini' configpath = os.path.join(now_path, fileA) if configpath and os.path.exists(configpath): cf = ConfigParser() cf.read(configpath) else: o = '{} is empty or not exists.'.format(configpath) print(o) sys.exit() print('邮箱配置加载成功') return cf sys.exit() def send_email_stmplib(email_config): # for smtplib use msg = email.mime.multipart.MIMEMultipart() msg['from'] = __format_addr('{}<{}>'.format(email_config[4],email_config[0])) msg['to'] = __format_addr('{}<{}>'.format(email_config[5],email_config[2])) msg['subject'] = email_config[3] if email_config[7]=='plain': txt = email.mime.text.MIMEText(email_config[6], email_config[7], 'utf-8') elif email_config[7]=='html': f1 = open(email_config[6], 'r', encoding="utf-8") content = f1.read() f1.close() txt = email.mime.text.MIMEText(content, email_config[7], 'utf-8') # plain or html msg.attach(txt) path_list=email_config[8:14] path_list=[p for p in path_list if p !=''] for path in path_list: part = MIMEApplication(open(path, 'rb').read()) part.add_header('Content-Disposition', 'attachment',filename=path.split('\\')[-1]) msg.attach(part) smtp.login(email_config[0], email_config[1]) smtp.sendmail(email_config[0], email_config[2], str(msg)) def send_email_zmail(econf, now_time): #for zmail use server = zmail.server(econf.get("basic", "inbox"), econf.get("basic", "inbox_auth_code")) bkfile = backupCmd(econf.get("content", "back_path"), now_time) # bkfile.append("/www/wwwroot/mrdocWB_data.20221205.tar.gz") # error 552, too large mail = { 'subject': econf.get("basic", "theme"), # Anything you want. 'attachments': bkfile, # Absolute path will be better, and bkfile can be a array. } html = False if html: with open('example.html','r') as f: content_html = f.read() mail["content_html"] = content_html else: mail['content_text'] = 'Backup data from mrdoc by zmail!' outbox = [i.strip() for i in econf.get("basic", "outbox").split(",")] addressee = [i.strip() for i in econf.get("basic", "addressee").split(",")] for i in range(len(outbox)): if not outbox[i]: continue server.send_mail((addressee[i], outbox[i]), mail) print('邮件发送进度:{}/{} {}<{}>已发送成功'.format(i+1,len(outbox), addressee[i], outbox[i])) time.sleep(2) for i in bkfile: os.remove(i) print('发送完成,关闭邮箱服务器') def backupCmd(path1, now_time): now_path = os.getcwd() if not os.path.exists(path1): print("[ERROR] path {} not exists.".format(path1)) sys.exit() os.chdir(path1) outfile = os.path.join(now_path, "mrdocWB.{}.tar.gz".format(now_time)) cmd = "tar cvzf {} ./config media/{} && echo finished || echo Failed".format(outfile, now_time[:6]) dd = os.popen(cmd) print("[INFO]", dd.read()) #filepath = os.path.join(path1, outfile) if os.path.getsize(outfile): return [outfile] else: print("[ERROR] Empty file {} from cmd".format(outfile)) sys.exit() if __name__ == "__main__": print_tool_info() econf = load_info() ########## Zmail ############## send_email_zmail(econf, now_time) sys.exit() ########## SMTPlib ############ print('Try connecting server') smtp = zmail.server(econf.get("basic", "inbox"), econf.get("basic", "inbox_auth_code")) print("Pop3: ", smtp.pop_able(), " SMTP:", smtp.smtp_able()) print('==================') outbox = econf.get("basic", "outbox").split(",") i = 0 for o in outbox: o = o.strip() i += 1 if o: email_config = [ econf.get("basic", "inbox"), econf.get("basic", "inbox_auth_code"), econf.get("basic", "outbox"), econf.get("basic", "theme"), econf.get("basic", "addresser"), econf.get("basic", "addressee"), econf.get("content", "body"), econf.get("content", "format") ] print(now_time, now_time[:6], now_path) os.chdir("..") print(os.getcwd()) backupCmd(econf.get("content", "back_path")) sys.exit() send_email_stmplib(email_config) a = round(random.uniform(1, 2), 2) time.sleep(a) print('邮件发送进度:{}/{} {}<{}>已发送成功'.format(i+1,len(outbox),email_config[5],email_config[2])) content = '【发送正常】 '+ str(email_config[5]) +' + '+ str(email_config[2]) log_path = now_path+r'\log\log-{} .txt'.format(now_time) f3 = open(log_path,'a') f3.write(content+ '\n') f3.close else: # Exception as err: content = '【出现错误】 '+ str(email_config[5]) +' + '+ str(email_config[2]) +' + '+ str(err) print(content) log_path = now_path+r'\log\log-{}.txt'.format(now_time) f3 = open(log_path,'a') f3.write(content+ '\n') f3.close smtp.quit() print('发送完成,关闭邮箱服务器') time.sleep(2) ```
laihui126
2023年12月19日 10:13
分享文档
收藏文档
上一篇
下一篇
微信扫一扫
复制链接
手机扫一扫进行分享
复制链接
关于 MrDoc
觅道文档MrDoc
是
州的先生
开发并开源的在线文档系统,其适合作为个人和小型团队的云笔记、文档和知识库管理工具。
如果觅道文档给你或你的团队带来了帮助,欢迎对作者进行一些打赏捐助,这将有力支持作者持续投入精力更新和维护觅道文档,感谢你的捐助!
>>>捐助鸣谢列表
微信
支付宝
QQ
PayPal
下载Markdown文件
分享
链接
类型
密码
更新密码