Differences between revisions 1 and 2
Revision 1 as of 2009-04-30 06:23:22
Size: 7155
Editor: ZoomQuiet
Comment:
Revision 2 as of 2009-11-28 14:57:12
Size: 7088
Editor: Elias
Comment: 删除对PageComment2组件的引用
Deletions are marked like this. Additions are marked like this.
Line 225: Line 225:
||<^>[[PageComment2]]||<^>[:/PageCommentData:PageCommentData]''||

TableOfContents

Include(ZPyUGnav)

用GMaild从控制台发送邮件的脚本

{{{邵志雄 <[email protected]> reply-to [email protected] to 二进制生存 <[email protected]> date Wed, Apr 29, 2009 at 22:21 subject |EasyScripts|用GMaild从控制台发送邮件的脚本 }}}

有时候需要备份些东西到邮箱,能够让脚本定时自动运行当然是最好! 抽时间用python写了这么个脚本,使用python-libgmail库 ( sudo apt-get install python-libgmail )

需求

发送邮件的代码都是现成的调用,主要是在易用性上做了些优化:

1、发送一句话,不需要正文,比如给邮件列表发个“求助。。。。。(如题)”之类的:
    msend -t  [email protected]  -s "求助,图形界面进不了,哈哈”

2、发个文件到自已的邮箱,一般用 -f "file1;file2;file3;dir2;dir3" ,发懒的时候不写 -f 也能用
    msend -t [email protected] -f readme.txt
    msend -t [email protected]  *.txt

3、发个文件或目录到某个邮箱,需要ZIP一下,(当然2和3可以混用)
    msend -t [email protected]  -z  ./pics/

基本上:

1、目标邮箱和主题必须写上;
2、如果有文件附件,可以不指定主题,脚本会把文件数当主题名(gmail的title里会显示正文的)
3、程序会自动判断文件和目录,如果是目录就会遍历
4、不管是文件还是目录,如果前缀指定了-z,就压缩后发送
5、没有前缀的参数一律当文件名

如果有需要,可以下载玩玩,运行msend不带参数就有用法,应该很明白了。

(还有什么稀奇古怪的想法?欢迎提出来!)

    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

代码

{{#!python #!/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 : else: 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: Full command:
    • msend --to=[email protected] --subject=title [--msg=body] [--files="file1;dir2"] [--zip="file1;dir2"]

    Example: ( edit ~/.msend for default sender account )

"""

  • 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,subject,msg,files):

    • print "FAIL"
    else:
    • for f in zip:
      • os.unlink(f)
      print "OK"

}}}


反馈

创建 by -- ZoomQuiet [DateTime(2009-04-30T06:23:22Z)]

MiscItems/2009-04-30 (last edited 2010-01-26 00:53:38 by WinuxPeng)