Python使用Gmail发邮件

Python使用Gmail发邮件,第1张

概述Python使用Gmail发邮件

下面是内存溢出 jb51.cc 通过网络收集整理的代码片段。

内存溢出小编现在分享给大家,也给大家做个参考。

有时候需要备份些东西到邮箱,能够让脚本定时自动运行当然是最好! 抽时间用python写了这么个脚本,使用python-libgmail库 ( sudo apt-get install python-libgmail )
 msend -t  [email protected] -s "求助,图形界面进不了,哈哈”
 msend -t [email protected] -f readme.txt    msend -t [email protected] *.txt
 msend -t [email protected] -z ./pics/
    Usage:        msend -t [email protected] -s Title        msend -t [email protected] {-s Title | -f file | -z file}    Full command:        msend [email protected] --subject=Title [--msg=body] [--files="file1;dir2"] [--zip="file1;dir2"]    Example: ( edit ~/.msend for default sender account )        msend -t [email protected] -s "just a test"        msend -t [email protected] -s "send all pic" -f ./mypics/        msend -t [email protected] -s "send files as zip" -z ./mytext/        msend -t [email protected] -s "send both" -f mytext -z mytext

#!/usr/bin/env python# -*- Coding: utf8 -*-import os,sysimport getoptimport libgmailclass 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,filenames=files)        else:            gmsg = libgmail.GmailComposedMessage(to,msg )        try :            if self.ga.sendMessage(gmsg):                return 0            else:                return 1        except Exception,err :            print err            return 1class 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 [email protected] -s Title        msend -t [email protected] {-s Title | -f file | -z file}    Full command:        msend [email protected] --subject=Title [--msg=body] [--files="file1;dir2"] [--zip="file1;dir2"]    Example: ( edit ~/.msend for default sender account )        msend -t [email protected] -s "just a test"        msend -t [email protected] -s "send all pic" -f ./mypics/        msend -t [email protected] -s "send files as zip" -z ./mytext/        msend -t [email protected] -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("[email protected]  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,files):        print "FAIL"    else:        for f in zip:            os.unlink(f)        print "OK"

以上是内存溢出(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

总结

以上是内存溢出为你收集整理的Python使用Gmail发邮件全部内容,希望文章能够帮你解决Python使用Gmail发邮件所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1199053.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存