中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

Python使用Gmail發(fā)郵件

2018-07-20    來源:open-open

容器云強勢上線!快速搭建集群,上萬Linux鏡像隨意使用
有時候需要備份些東西到郵箱,能夠讓腳本定時自動運行當(dāng)然是最好! 抽時間用python寫了這么個腳本,使用python-libgmail庫 ( sudo apt-get install python-libgmail )

需求

發(fā)送郵件的代碼都是現(xiàn)成的調(diào)用,主要是在易用性上做了些優(yōu)化:

1、發(fā)送一句話,不需要正文,比如給郵件列表發(fā)個“求助。。。。。(如題)”之類的:

 msend -t  list@domain.com -s "求助,圖形界面進不了,哈哈”

2、發(fā)個文件到自已的郵箱,一般用 -f "file1;file2;file3;dir2;dir3" ,發(fā)懶的時候不寫 -f 也能用

 msend -t my@gmail.com -f readme.txt
    msend -t my@gmail.com *.txt

3、發(fā)個文件或目錄到某個郵箱,需要ZIP一下,(當(dāng)然2和3可以混用)

 msend -t friend@domain.com -z ./pics/

基本上:

1、目標(biāo)郵箱和主題必須寫上; 2、如果有文件附件,可以不指定主題,腳本會把文件數(shù)當(dāng)主題名(gmail的title里會顯示正文的) 3、程序會自動判斷文件和目錄,如果是目錄就會遍歷 4、不管是文件還是目錄,如果前綴指定了-z,就壓縮后發(fā)送 5、沒有前綴的參數(shù)一律當(dāng)文件名 如果有需要,可以下載玩玩,運行msend不帶參數(shù)就有用法,應(yīng)該很明白了。

(還有什么稀奇古怪的想法?歡迎提出來!)

    Usage:
        msend -t user@domain.com -s title
        msend -t user@domain.com {-s title | -f file | -z file}

    Full command:
        msend --to=user@domain.com --subject=title [--msg=body] [--files="file1;dir2"] [--zip="file1;dir2"]

    Example: ( edit ~/.msend for default sender account )
        msend -t user@domain.com -s "just a test"
        msend -t user@domain.com -s "send all pic" -f ./mypics/
        msend -t user@domain.com -s "send files as zip" -z ./mytext/
        msend -t user@domain.com -s "send both" -f mytext -z mytext

代碼

#!/usr/bin/env python
# -*- coding: utf8 -*-

import os ,sys
import getopt
import libgmail

class GmailSender(libgmail.GmailAccount) :
    def __init__(self,myacct,passwd):
        self.myacct = myacct
        self.passwd = passwd

        proxy = os.getenv("http_proxy")
        if proxy :
            libgmail.PROXY_URL = proxy

        try:
            self.ga = libgmail.GmailAccount(myacct,passwd)
            self.ga.login()
        except libgmail.GmailLoginFailure,err:
            print "Login failed. (Check $HOME/.msend?)\n",err
            sys.exit(1)
        except Exception,err:
            print "Login failed. (Check network?)\n",err
            sys.exit(1)

    def sendMessage(self,to,subject,msg,files):
        if files :
            gmsg = libgmail.GmailComposedMessage(to,subject,msg,filenames=files)
        else:
            gmsg = libgmail.GmailComposedMessage(to, subject, msg )

        try :
            if self.ga.sendMessage(gmsg):
                return 0
            else:
                return 1
        except Exception,err :
            print err
            return 1

class TOOLS :
    def extrPath(path):
        list=[]
        for root,dirs,files in os.walk(path):
            for f in files:
                list.append("%s/%s"%(root,f))
        return list

    extrPath = staticmethod(extrPath)

if __name__ == "__main__":

    to=subject=zip=None
    msg=""
    files=[]
    zip=[]

    # getopt
    try:
        opts,args = getopt.getopt(sys.argv[1:],
                't:s:m:f:d:z:',
                [ 'to=', 'subject=', 'msg=', 'files=',"dir=","zip=" ])
    except getopt.GetoptError,err:
        print str(err)
        sys.exit(2)

    for o,a in opts:
        if o in [[--to","-t]]:
            to = a
        elif o in [[--msg","-m]]:
            msg = a + "\n====================\n"
        elif o in [[--subject","-s]]:
            subject = a
        elif o in [[--files","-f]]:
            if a.find(';') > 0:
                files += a.split(';')
            else:
                files += a.replace('\n',' ').split(' ')
        elif o in [[--dir","-d]]:
            if a.find(';') > 0:
                files += a.split(';')
            else:
                files += a.replace('\n',' ').split(' ')
        elif o in [[--zip","-z]]:
            if a.find(';') > 0:
                zip += a.split(';')
            else:
                zip += a.replace('\n',' ').split(' ')

    # extrPath
    files += args

    if len(files)>0:
        msg += "\n=====FILE=====\n"
    for f in files:
        if os.path.isfile(f):
            msg += "%s\n"%f
        elif os.path.isdir(f):
            files.remove(f)
            ret = TOOLS.extrPath(f)
            files += ret;
            msg += "\n=====FOLDER[%s]=====\n"%f
            msg += "\n".join(ret)

    for f in zip:
        name=f.replace('/','_')
        cmd = "zip -r /tmp/%s.zip %s 1>/tmp/%s.log 2>&1"%(name,f,name)
        os.system(cmd)
        msg += "\n=====ZIP[%s]=======\n"%f
        msg += open("/tmp/%s.log"%name).read()
        os.unlink("/tmp/%s.log"%name)
        zip.remove(f)
        zip.append("/tmp/%s.zip"%name)

    files += zip
    #print msg
    #sys.exit(0)
    if not subject and len(files)>0:
        subject="Send %d files."%len(files)

    if not to or not subject:
        print """
    Usage:
        msend -t user@domain.com -s title
        msend -t user@domain.com {-s title | -f file | -z file}

    Full command:
        msend --to=user@domain.com --subject=title [--msg=body] [--files="file1;dir2"] [--zip="file1;dir2"]

    Example: ( edit ~/.msend for default sender account )
        msend -t user@domain.com -s "just a test"
        msend -t user@domain.com -s "send all pic" -f ./mypics/
        msend -t user@domain.com -s "send files as zip" -z ./mytext/
        msend -t user@domain.com -s "send both" -f mytext -z mytext
"""
        sys.exit(3)

    conf = "%s/%s" % ( os.getenv("HOME"), ".msend" )
    if not os.path.exists(conf):
        open(conf,"wb").write("yourname@gmail.com  yourpassword")
        print """\n  Edit $HOME/.msend first.\n"""
        sys.exit(3)

    myacct,passwd = open( conf ).read().split()
    gs = GmailSender( myacct,passwd )
    if gs.sendMessage(to,subject,msg,files):
        print "FAIL"
    else:
        for f in zip:
            os.unlink(f)
        print "OK"

標(biāo)簽: 代碼 腳本

版權(quán)申明:本站文章部分自網(wǎng)絡(luò),如有侵權(quán),請聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點!
本站所提供的圖片等素材,版權(quán)歸原作者所有,如需使用,請與原作者聯(lián)系。

上一篇:獲取中國省市的Python代碼

下一篇:python人臉識別