Use Python to send mail attachments to regularly back up MySQL tutorials _python

Source: Internet
Author: User
Tags mysql backup python script

Recently migrated WordPress, the system upgraded to CentOS 6, a very strange problem, in the original CentOS 5.8 under the normal time to back up the database and sent by mail script can not send attachments, the other is normal, the message content is uuencode generated file encoding, But there is no attachment. And can not find the reason, hope to have know the generous enlighten.

To solve this problem, I wrote a mail client with Python, and I can send an attachment, which is a command-line program. Don't say much nonsense. Paste code:

#!/usr/bin/env python #-*-coding:utf8-*-' #==================================================================== ========= # FileName:mail.py # desc:to Send email # author:cold # email:wh_linux@126.com # Homepage:htt p://www.linuxzen.com # version:0.0.1 # lastchange:2012-04-21 16:37:20 # History: #================================= ============================================ ' ' is used to send mail, you can send the attachment command line Program ' Import smtplib from email.mime.text import M  Imetext from Email.mime.multipart import mimemultipart import SYS # print 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 con Tent use. To end-h specify SMTP server host-u which user login the SMTP Server,and must with it domain-p the password o f the SMTP user-t The email recipient,multiple addresses can use ', ' split-a Add attachment-n secify N
Ame in the email
  Author:cold (wh_linux@126.com) homepge:http://www.linuxzen.com ' ' # All 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.argv[i], ' and please use-h to help! ' Sys.exit (3) # If it is-h or if there are no command-line arguments, help 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) # The following is to get the contents of each parameter 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=tr  UE Try: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 = None Try:mail_host = Sys.argv[sys.argv.index (' h ') +1] Exc  EPT 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_user Email.split (' @ ') [0] Mail_postfix = mail_useremail.split (' @ ') [1] try:mail_pass = Sys.argv[sys.argv.index (' P ') +1] Exce PT valueerror:mail_pass = ' # define 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 ' Error:no input file of attachments ' return False # There are attachments create an instance with an attachment msg = Mimemultipart () # construct attachment A tt = mimetext (open ATTRPAth, ' RB '). Read (), ' base64 ', ' UTF8 ') att["content-type"] = ' application/octest-stream ' att[' content-disposition '] =
    ' Attachment;filename= ' + attrname + ' "' Msg.attach (att) msg.attach (content) Else: # No accountability Create an instance of a text msg = Mimetext (content) # 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_list, Msg.as_string ()) S.close () return True except Exception, E:print str (e) return False if __nam
      e__ = = ' __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"

Save the script as Pymail and place it under/usr/bin/and give it permission to execute:

chmod +x/usr/bin/pymail

You can specify the SMTP sender server by using-H, and by default, specify-H requires authentication, so you need the SMTP server to support authentication, and you need to specify the username (with @ domain name) and-p to specify the password. If you do not specify-H, the local SMTP server is used, and authentication is not required by default, so the local SMTP server does not support authentication and does not need to specify-U,-P parameters

-t specifies that multiple recipients are available, number split.
-a Specifies the attachment path
-n Specifies the attachment name (can be omitted)
-h Displays help information.
-s specifies the message subject

After execution, you will be asked to enter the content of the message, finish. You can also use the pipe below to give several examples:

#使用本地smtp服务发送
Echo ' linuxzen.com backup ' | pymail-s "Linuxzen backup"-t 123456@qq.com-a/tmp/linuxzen.tar.gz
#  Use 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 pipelines 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 Hello this is
a test mail
.

The following MySQL scheduled backup scripts are used before:

#!/bin/bash
Export PATH=/USR/KERBEROS/SBIN:/USR/KERBEROS/BIN:/USR/LOCAL/SBIN:/USR/LOCAL/BIN:/SBIN:/BIN:/USR /sbin:/usr/bin:/root/bin
date= ' DATE +%y%m%d '
mysqldump-u root blogdata >/tmp/blogdate. $DATE ". SQL
cd/tmp
tar-zcf blogdata." $DATE ". sql.tar.gz blogdata." $DATE ". SQL
uuencode 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

This script is then executed with crontab, which is said to work correctly under centos5.x, but not with attachments under CentOS6, so using our own Python script script reads as follows:

#!/bin/bash
Export PATH=/USR/KERBEROS/SBIN:/USR/KERBEROS/BIN:/USR/LOCAL/SBIN:/USR/LOCAL/BIN:/SBIN:/BIN:/USR /sbin:/usr/bin:/root/bin
date= ' DATE +%y%m%d '
mysqldump-u root blogdata >/tmp/myblog. $DATE ". SQL
cd/tmp
tar-zcf blogdata." $DATE ". sql.tar.gz myblog." $DATE ". SQL
echo ' mysql backup ' | pymail-u linuzen@126.com-p linuxzen.com-h smtp.126.com-s ' mysql backup '-a/tmp/b Logdata. " $DATE ". Sql.tar.gz-t 123456@qq.com


We use 126 mailboxes to send this so that we can stop the SendMail from the band:
Service SendMail Stop
chkonfig--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.