tutorial on using Python to send mail attachments for scheduled backups of MySQL

Source: Internet
Author: User
Tags mysql backup python script
Recently migrated WordPress, System upgrade to CentOS 6, a very strange problem, in the original CentOS 5.8 under the normal scheduled backup database and sent by mail script can not send attachments, others are normal, the message content is also uuencode generated file encoding, But there is no attachment. And can not find out the reason, hope to know the generous enlighten.

To solve this problem, I used Python to write a mail client, can send an attachment, is a command-line program. Don't say much. Paste code:

#!/usr/bin/env python#-*-Coding:utf8-*-"#==================================================================== =========# filename:mail.py# desc:to send email# author:cold# email:wh_linux@126.com# homepage:http://w ww.linuxzen.com# version:0.0.1# lastchange:2012-04-21 16:37:20# history:#========================================= ==================================== "" is used to send mail, can send Attachment command line program "" Import smtplibfrom email.mime.text Import Mimetextfrom email.mime.multipart import mimemultipartimport sys# print help 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 login the SMTP Server,and must with it domain-p the password of T  He 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 ']# get option length Argvnum = Len (sys.argv) # Detect command line arguments for I in range (Argvnum): if (i%2! = 0): if (Sys.argv[i] not in options): print ' unknow option ', Sys.arg      V[i], ', please use-h see help! ' Sys.exit (3) # Display Help if it is-h or no command-line argument try:if sys.argv[1] = = '-h ' or len (sys.argv) = = 0:helpinfo () except:helpinfo () # Detect-N Parameter if ('-n ' in sys.argv) and ('-a ' not in sys.argv): print ' Error:option "-n" must use After-a ' Sys.exit (2) # Below are the parameters that are obtained in each parameter Capacitance Try:tmpmailto = Sys.argv[sys.argv.index ('-t ') + 1] if ', ' in Tmpmailto:mailto = Tmpmailto.split (', ') Else:mai LTO = [tmpmailto,]except valueerror:print ' error:need Mail Recipient ' sys.exit (1) Haveattr=truetry:attrpath = Sys.arg V[sys.argv.index ('-a ') + 1] try:attrname = Sys.argv[sys.argv.index ('-n ') +1] except valueerror:attrname = ATTRP Ath.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_u Seremail = ' 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 = ' # definition mail send function def send_mail (to_list, Sub, content, Haveattr, Attrpath, attrname): Me = Mail_user + "<" + mail_user+ "@" +mail_postfix + ">" # to determine if there is an attachment if (haveattr): if (not Attrpath): print ' Er Ror:no input file of attachments ' return False # There is an attachment to create an instance with an attachment msg = Mimemultipart () # construct attachment att = MIME Text (Open (Attrpath, ' RB '). Read (), ' base64 ', ' UTF8 ') att["content-type"] = ' application/octest-stream ' att[' Content-di Sposition "] = ' Attachment;filenAme= "' + attrname + '" ' Msg.attach (att) msg.attach (mimetext (content)) Else: # No responsibility to create an instance of text msg = Mimetext (conten T) # message header msg[' Subject ' = Sub msg[' from ' = Me msg[' to '] = ";". Join (To_list) Try: # send mail s = smtplib. SMTP () s.connect (mail_host) if (mail_host! = ' 127.0.0.1 '): S.login (Mail_user, Mail_pass) S.sendmail (Me, to_l ist, msg.as_string ()) S.close () return True except Exception, E:print str (e) return falseif __name__ = = ' __m Ain__ ': 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, attr Path, attrname): print "Success" Else:print "Failed"

Save this script as Pymail and put it under/usr/bin/, and give it permission to execute:

chmod +x/usr/bin/pymail

You can use-H to specify the SMTP outgoing server, by default the specified-H requires authentication, so the SMTP server is required to support authentication, and you need-U to specify the user name (with "@ domain name"),-p Specify the password. If you do not specify-H will use the local SMTP server, the default does not require authentication, so the local SMTP server can not support authentication, and do not need to specify the-U,-P parameter

-t specifies that more than one recipient is available, the number is split.
-a Specifies the attachment path
-n Specifies the name of the attachment (can be omitted)
-h Displays help information.
-s Specifies the subject of the message

After the execution will be asked to enter the message content, finished writing. You can also use the pipe below to give a few examples:

#使用本地smtp服务发送echo ' linuxzen.com backup ' | Pymail-s "Linuxzen Backup"-t 123456@qq.com-a/tmp/linuxzen.tar.gz# using 126 mailbox to send 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 # do not send pymail-u linuxzen@126.com-p linuxzen.com-h smtp.126.com-s ' Hello World '-t 123456@qq.com-a/tmp/linuxzen.tar with pipeline . Gzhellothis is a test mail.

Before using the MySQL scheduled backup script:

#!/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

No command uuencode install Sharutils package

Yum-y Install Sharutils

Then use the crontab call this script timed execution, said the script in the centos5.x under the normal work, but placed under the CentOS6 without attachments, so use our own Python script script content as follows:

#!/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

We use 126 mailboxes to send this to stop the SendMail:

Service SendMail Stopchkonfig--del sendmail
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    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.