用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

代码

   1 #!/usr/bin/env python
   2 # -*- coding: utf8 -*-
   3 
   4 import os ,sys
   5 import getopt
   6 import libgmail
   7 
   8 class GmailSender(libgmail.GmailAccount) :
   9     def __init__(self,myacct,passwd):
  10         self.myacct = myacct
  11         self.passwd = passwd
  12 
  13         proxy = os.getenv("http_proxy")
  14         if proxy :
  15             libgmail.PROXY_URL = proxy
  16 
  17         try:
  18             self.ga = libgmail.GmailAccount(myacct,passwd)
  19             self.ga.login()
  20         except libgmail.GmailLoginFailure,err:
  21             print "Login failed. (Check $HOME/.msend?)\n",err
  22             sys.exit(1)
  23         except Exception,err:
  24             print "Login failed. (Check network?)\n",err
  25             sys.exit(1)
  26 
  27 
  28     def sendMessage(self,to,subject,msg,files):
  29         if files :
  30             gmsg = libgmail.GmailComposedMessage(to,subject,msg,filenames=files)
  31         else:
  32             gmsg = libgmail.GmailComposedMessage(to, subject, msg )
  33 
  34         try :
  35             if self.ga.sendMessage(gmsg):
  36                 return 0
  37             else:
  38                 return 1
  39         except Exception,err :
  40             print err
  41             return 1
  42 
  43 class TOOLS :
  44     def extrPath(path):
  45         list=[]
  46         for root,dirs,files in os.walk(path):
  47             for f in files:
  48                 list.append("%s/%s"%(root,f))
  49         return list
  50 
  51     extrPath = staticmethod(extrPath)
  52 
  53 if __name__ == "__main__":
  54     
  55     to=subject=zip=None
  56     msg=""
  57     files=[]
  58     zip=[]
  59     
  60     # getopt
  61     try:
  62         opts,args = getopt.getopt(sys.argv[1:],
  63                 't:s:m:f:d:z:',
  64                 [ 'to=', 'subject=', 'msg=', 'files=',"dir=","zip=" ])
  65     except getopt.GetoptError,err:
  66         print str(err)
  67         sys.exit(2)
  68     
  69     for o,a in opts:
  70         if o in [[--to","-t]]:
  71             to = a
  72         elif o in [[--msg","-m]]:
  73             msg = a + "\n====================\n"
  74         elif o in [[--subject","-s]]:
  75             subject = a
  76         elif o in [[--files","-f]]:
  77             if a.find(';') > 0:
  78                 files += a.split(';')
  79             else:
  80                 files += a.replace('\n',' ').split(' ')
  81         elif o in [[--dir","-d]]:
  82             if a.find(';') > 0:
  83                 files += a.split(';')
  84             else:
  85                 files += a.replace('\n',' ').split(' ')
  86         elif o in [[--zip","-z]]:
  87             if a.find(';') > 0:
  88                 zip += a.split(';')
  89             else:
  90                 zip += a.replace('\n',' ').split(' ')
  91 
  92     # extrPath
  93     files += args
  94     
  95     if len(files)>0:
  96         msg += "\n=====FILE=====\n"
  97     for f in files:
  98         if os.path.isfile(f):
  99             msg += "%s\n"%f
 100         elif os.path.isdir(f):
 101             files.remove(f)
 102             ret = TOOLS.extrPath(f)
 103             files += ret;
 104             msg += "\n=====FOLDER[%s]=====\n"%f
 105             msg += "\n".join(ret)
 106 
 107     for f in zip:
 108         name=f.replace('/','_')
 109         cmd = "zip -r /tmp/%s.zip %s 1>/tmp/%s.log 2>&1"%(name,f,name)
 110         os.system(cmd)
 111         msg += "\n=====ZIP[%s]=======\n"%f
 112         msg += open("/tmp/%s.log"%name).read()
 113         os.unlink("/tmp/%s.log"%name)
 114         zip.remove(f)
 115         zip.append("/tmp/%s.zip"%name)
 116 
 117     files += zip
 118     #print msg
 119     #sys.exit(0)
 120     if not subject and len(files)>0:
 121         subject="Send %d files."%len(files)
 122 
 123     if not to or not subject:
 124         print """
 125     Usage:
 126         msend -t [email protected] -s title
 127         msend -t [email protected] {-s title | -f file | -z file}
 128 
 129     Full command:
 130         msend [email protected] --subject=title [--msg=body] [--files="file1;dir2"] [--zip="file1;dir2"]
 131 
 132     Example: ( edit ~/.msend for default sender account )
 133         msend -t [email protected] -s "just a test"
 134         msend -t [email protected] -s "send all pic" -f ./mypics/
 135         msend -t [email protected] -s "send files as zip" -z ./mytext/
 136         msend -t [email protected] -s "send both" -f mytext -z mytext
 137 """
 138         sys.exit(3)
 139 
 140     conf = "%s/%s" % ( os.getenv("HOME"), ".msend" )
 141     if not os.path.exists(conf):
 142         open(conf,"wb").write("[email protected]  yourpassword")
 143         print """\n  Edit $HOME/.msend first.\n"""
 144         sys.exit(3)
 145 
 146     myacct,passwd = open( conf ).read().split()
 147     gs = GmailSender( myacct,passwd )
 148     if gs.sendMessage(to,subject,msg,files):
 149         print "FAIL"
 150     else:
 151         for f in zip:
 152             os.unlink(f)
 153         print "OK"


反馈

创建 by -- ZoomQuiet [2009-04-30 06:23:22]

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

Loading