国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

使用Python發送郵件附件以定時備份MySQL的教程

2020-02-23 00:51:08
字體:
來源:轉載
供稿:網友

最近遷移了wordpress,系統升級為CentOS 6,很奇怪的一個問題,在原來CentOS 5.8下用的很正常的定時備份數據庫并通過郵件發送的腳本不能發送附件,其他都正常,郵件內容也是uuencode生成的文件編碼,但是就是不產生附件.而且找不出原因,望有知道的不吝賜教.

為了解決這一問題,我用Python寫了一個mail客戶端,可以發送附件,是一個命令行程序.廢話不多說.貼代碼:

#!/usr/bin/env python#-*- coding: utf8 -*-'''#=============================================================================#   FileName: mail.py#     Desc: To send email#    Author: cold#    Email: wh_linux@126.com#   HomePage: http://www.linuxzen.com#   Version: 0.0.1#  LastChange: 2012-04-21 16:37:20#   History:#=============================================================================''''''用于發送郵件,可以發送附件命令行程序'''import smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartimport sys# 打印幫助信息def helpinfo():  print '''  Useage: pymail -u user@domain -p passwd -h smtp server host -t to who [-a attachment file path] [-n attachment name]  Useage: email content use . to end  -h specify smtp server host  -u which user you login the smtp server,and must with it domain  -p the password of the smtp user  -t The email recipient,multiple addresses can use ',' split  -a Add attachment  -n Secify attachment name in the email  Author:cold(wh_linux@126.com)  Homepge:http://www.linuxzen.com  '''# 所有選項options = ['-t', '-a', '-n', '-h', '-u', '-p', '-s']# 獲取選項長度argvnum = len(sys.argv)# 檢測命令行參數for i in range(argvnum):  if ( i %2 != 0):    if (sys.argv[i] not in options):      print 'Unknow option ', sys.argv[i] , ', Please use -h see help!'      sys.exit(3)# 如果是-h或者沒有命令行參數則顯示幫助try:  if sys.argv[1] == '-h' or len(sys.argv) == 0:    helpinfo()except:  helpinfo()# 檢測-n參數if ('-n' in sys.argv) and ('-a' not in sys.argv):  print 'Error:option "-n" must use after -a'  sys.exit(2)# 下面則是獲取各個參數內容try:  tmpmailto = sys.argv[sys.argv.index('-t') + 1]  if ',' in tmpmailto:    mailto = tmpmailto.split(',')  else:    mailto = [tmpmailto,]except ValueError:  print 'Error: need Mail Recipient'  sys.exit(1)haveattr=Truetry:  attrpath = sys.argv[sys.argv.index('-a') + 1]  try:    attrname = sys.argv[sys.argv.index('-n') +1 ]  except ValueError:    attrname = attrpath.split('/')[-1]except:  attrname = None  haveattr = False  attrpath = Nonetry:  mail_host = sys.argv[sys.argv.index('-h') +1]except ValueError:  print 'Waring: No specify smtp server use 127.0.0.1'  mail_host = '127.0.0.1'try:  mail_useremail = sys.argv[sys.argv.index('-u') +1]except ValueError:  print 'Waring: No specify user, use root'  mail_useremail = 'root@localhost'try:  mail_sub = sys.argv[sys.argv.index('-s') + 1]except:  mail_sub = 'No Subject'mail_user = mail_useremail.split('@')[0]mail_postfix = mail_useremail.split('@')[1]try:  mail_pass = sys.argv[sys.argv.index('-p') +1]except ValueError:  mail_pass = ''# 定義郵件發送函數def send_mail(to_list, sub, content, haveattr, attrpath, attrname):  me = mail_user + "<" + mail_user+"@"+mail_postfix +">"  # 判斷是否有附件  if (haveattr):    if (not attrpath):      print 'Error : no input file of attachments'      return False    # 有附件則創建一個帶附件的實例    msg = MIMEMultipart()    # 構造附件    att = MIMEText(open(attrpath, 'rb').read(),'base64', 'utf8')    att["Content-Type"] = 'application/octest-stream'    att["Content-Disposition"] = 'attachment;filename="'+ attrname +'"'    msg.attach(att)    msg.attach(MIMEText(content))  else:    # 無責創建一個文本的實例    msg = MIMEText(content)  # 郵件頭  msg['Subject'] = sub  msg['From'] = me  msg['To'] = ";".join(to_list)  try:    # 發送郵件    s = smtplib.SMTP()    s.connect(mail_host)    if (mail_host != '127.0.0.1'):      s.login(mail_user, mail_pass)    s.sendmail(me, to_list, msg.as_string())    s.close()    return True  except Exception, e:    print str(e)    return Falseif __name__ == '__main__':  try:    content = ''    while True:      c = raw_input('')      if c == '.':        break      content += c + '/n'  except EOFError:    for line in sys.stdin:      content += line  if send_mail(mailto, mail_sub, content, haveattr, attrpath, attrname):    print "Success"  else:    print "Failed"            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 金坛市| 丹巴县| 江安县| 南昌县| 深水埗区| 西宁市| 丘北县| 仪陇县| 大姚县| 元阳县| 阿拉善右旗| 临泉县| 宿迁市| 司法| 九寨沟县| 措美县| 肥乡县| 耒阳市| 洛浦县| 中阳县| 通辽市| 汨罗市| 崇阳县| 虞城县| 开封县| 隆安县| 长垣县| 南昌县| 板桥市| 灌阳县| 张家口市| 旅游| 富民县| 崇阳县| 北京市| 巴彦淖尔市| 北京市| 城步| 彰武县| 蚌埠市| 牡丹江市|