Using Python to send email attachments to regularly back up MySQL tutorials, pythonmysql

Source: Internet
Author: User
Tags mysql backup

Using Python to send email attachments to regularly back up MySQL tutorials, pythonmysql

Wordpress was recently migrated and the system was upgraded to CentOS 6. A strange problem is that the normally used regular backup database in CentOS 5.8 and the script sent by mail cannot send attachments, the email content is also the file encoding generated by uencode, but no attachment is generated. I can't find the reason, but I hope I can tell you what I know.

To solve this problem, I wrote a mail client using Python, which can send attachments. It is a command line program. I don't talk much about it. Post the Code:

#! /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: 16:37:20 # History: #===================================================== ================================================='' ''' is used to send emails, you can send the Attachment Command Line program ''' im Port smtplibfrom email. mime. text import MIMETextfrom email. mime. multipart import MIMEMultipartimport sys # print the help information 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 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 ''' # All options = ['-t','-A', '-n','-h ','-U', '-p ', '-S'] # obtain the option length argvnum = len (sys. argv) # Check the command line parameter 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) # if it is-h or there is no command line parameter, the help try: if sys. argv [1] = '-H' or len (sys. argv) = 0: helpinfo () handle T: helpinfo () # Check-n parameter if ('-n' in sys. argv) and ('-a' not in sys. argv): print 'error: option "-n" must use after-a' sys. exit (2) # obtain the parameters. try: tmpmailto = sys. argv [sys. argv. index ('-t') + 1] if', 'in tmpmailto: mailto = tmpmailto. split (',') else: mailto = [tmpmailto,] cannot t 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] partition t ValueError: attrname = attrpath. split ('/') [-1] partition T: attrname = None haveattr = False attrpath = Nonetry: mail_host = sys. argv [sys. argv. index ('-H') + 1] partition t ValueError: print 'waring: No specify smtp server use 127.0.0.1 'mail_host = '2017. 0.0. 1 'try: mail_useremail = sys. argv [sys. argv. index ('-U') + 1] partition t ValueError: print 'waring: No specify user, use root 'mail_useremail = 'root @ localhost' try: mail_sub = sys. argv [sys. argv. index ('-S') + 1] couldn t: mail_sub = 'no subobject' mail _ user = mail_useremail.split (' @ ') [0] mail_postfix = mail_useremail.split ('@') [1] try: mail_pass = sys. argv [sys. argv. index ('-p') + 1] couldn t ValueError: mail_pass = ''# Define the mail sending function def send_mail (to_list, sub, content, haveattr, attrpath, attrname ): me = mail_user + "<" + mail_user + "@" + mail_postfix + ">" # determine whether there is an attachment if (haveattr): if (not attrpath): print 'error: no input file of attachments 'Return False # create an instance with an attachment msg = MIMEMultipart () # create an attachment att = MIMEText (open (attrpath, 'rb '). read (), 'base64', 'utf8') att ["Content-Type"] = 'application/octest-stream' att ["Cont Ent-Disposition "] = 'attachment; filename =" '+ attrname +' "'msg. attach (att) msg. attach (MIMEText (content) else: # create a text instance msg = MIMEText (content) # mail header msg ['subobject'] = sub msg ['from'] = me msg ['to'] = ";". join (to_list) try: # send mail s = smtplib. SMTP () s. connect (mail_host) if (mail_host! = '2017. 0.0.1 '): s. login (mail_user, mail_pass) s. sendmail (me, to_list, msg. as_string () s. close () return True except t Exception, e: print str (e) return Falseif _ name _ = '_ main _': try: content = ''while True: c = raw_input ('') if c = '. ': break content + = c +' \ n' handle T EOFError: for line in sys. stdin: content + = line if send_mail (mailto, mail_sub, content, haveattr, attrpath, attrname): print "Success" else: print "Failed"

Save the script as pymail and put it under/usr/bin/, and grant it the execution permission:

chmod +x /usr/bin/pymail

You can use-h to specify the smtp sending server. By default, the-h authentication is required, so the smtp server must support authentication, at the same time, you need to specify the user name (Add "@ domain name") with-u, and specify the password with-p. if-h is not specified, the local smtp server will be used. authentication is not required by default. Therefore, the local smtp server cannot support authentication without specifying the-u and-p parameters.

-T specifies multiple recipients, separated by numbers.
-A: Specify the attachment path.
-N specifies the attachment name (which can be omitted)
-H: displays help information.
-S specifies the Email Subject

After the task is executed, you must enter the email content. After the task is completed, you can use the pipeline to provide several instances:

# Use the local smtp service to send echo 'linuxzen. com backup '| pymail-s "Linuxzen backup"-t 123456@qq.com-a/tmp/linuxzen.tar.gz # Use the 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 use a pipeline to send pymail-u linuxzen@126.com-p linuxzen.com-h smtp.126.com-s 'Hello world'-t 123456@qq.com-a/tmp/linuxzen.tar.gz Hellothis is a test mail.

The following is the script for mysql scheduled backup:

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

You can install the sharutils package without the command uuencode.

yum -y install sharutils

Then, use crontab to call this script for regular execution. As mentioned above, this script works normally in CentOS5.x, but it does not contain any attachment in CentOS6. Therefore, use the python script we have compiled 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 can use 126 mail to send the built-in sendmail to stop:
service sendmail stopchkonfig --del sendmail

 

Related Article

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.