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

來源:互聯網
上載者:User

最近遷移了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"

將這個指令碼儲存為pymail放到/usr/bin/下,並賦予其執行許可權:

chmod +x /usr/bin/pymail

可以使用 -h指定smtp發件伺服器,預設認為指定-h需要認證, 所以就需要smtp伺服器支援認證,同時需要-u指定使用者名稱(需加"@網域名稱"),-p指定密碼. 如果不指定-h就會使用本地smtp伺服器,預設不需要認證,所以本地的smtp伺服器就不能支援認證,同時不需指定-u,-p參數

-t 指定收件者多個可用,號分割.
-a 指定附件路徑
-n 指定附件名(可省略)
-h 顯示協助資訊.
-s 指定郵件主題

執行後會要求輸入郵件內容,寫完用.結束 也可以用管道下面給出幾個執行個體:

#使用本地smtp服務發送echo 'linuxzen.com backup' | pymail -s "Linuxzen backup" -t 123456@qq.com -a /tmp/linuxzen.tar.gz# 使用126郵箱發送echo 'linuxzen.com backup' | pymail -u linuxzen@126.com -p linuxzen.com -h smtp.126.com -s 'Linuxzen backup " -t 123456@qq.com -a /tmp/linuxzen.tar.gz # 不使用管道發送pymail -u linuxzen@126.com -p linuxzen.com -h smtp.126.com -s 'hello world' -t 123456@qq.com -a /tmp/linuxzen.tar.gzHellothis is a test mail.

下面之前使用的mysql定時備份的指令碼:

#!/bin/bashexport PATH=/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/binDATE=`date +%Y%m%d`mysqldump -u root blogdata > /tmp/blogdate."$DATE".sqlcd /tmptar -zcf blogdata."$DATE".sql.tar.gz blogdata."$DATE".sqluuencode blogdata."$DATE".sql.tar.gz blogdata."$DATE".sql.tar.gz | mail -s 'MySQL Backup' 123456@qq.com

沒有命令uuencode安裝sharutils包即可

yum -y install sharutils

然後使用crontab調用這個指令碼定時執行,前面說了 這個指令碼在CentOS5.x下正常工作,但是放到CentOS6下就不帶附件,所以使用我們自己編寫的python指令碼指令碼內容如下:
 

#!/bin/bashexport PATH=/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/binDATE=`date +%Y%m%d`mysqldump -u root blogdata > /tmp/myblog."$DATE".sqlcd /tmptar -zcf blogdata."$DATE".sql.tar.gz myblog."$DATE".sqlecho 'MySQL backup' | pymail -u linuzen@126.com -p linuxzen.com -h smtp.126.com -s 'MySQL backup' -a /tmp/blogdata."$DATE".sql.tar.gz -t 123456@qq.com
我們使用126郵箱來發送 這樣就可以把內建的sendmail 停掉:
service sendmail stopchkonfig --del sendmail

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.