zoukankan      html  css  js  c++  java
  • Python编写的Linux邮件发送工具

    之前有用过Linux自带的mail工具来定时发送邮件,但是要装mailx还有配mail.rc,这还比较正常,关键是到了ubantu下这工具用起来真是操蛋,如果哪天其他的unix like操作系统也有需求,那就太麻烦了,所以我用自带的python2.6.6和自带的邮件相关的库写了个小工具,使用步骤如下:

    一、申请一个163邮箱,作为发件箱。

    不用qq邮箱是因为,qq邮箱的SMTP服务器需要独立的密码,比较麻烦一点。

    二、创建如下脚本,改名为SendMail.py:

    注意将以下脚本中的from_addr和password改为你自己的163邮箱和密码即可。

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    from email.header import Header
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.mime.application import MIMEApplication
    import os,sys
    import smtplib
    import getopt
    
    #使用帮助
    def usage():
        print('''Usage: 
        SendMail.py [Options]
        eg. SendMail.py -s "邮件标题" -c "邮件正文" -d "xxx@xxx.com,yyy@yyy.com" --content-file mail_content.txt --attach attachment.log
    Options:
        -h/--help 显示此帮助
        -s 邮件标题,例如: -s "这里是邮件标题"
        -c 邮件正文,例如: -c "这里是邮件正文"
        -d 邮件接收地址,例如: -d "xxx@xxx.com,yyy@yyy.com"
        --content-file 包含邮件正文的文件,例如: --content-file mail_content.txt
        --attach 附件,可以是绝对或相对路径,例如: --attach attachment.log 或者 --attach /var/log/attachment.log
        Ps:目前此脚本只支持一个附件,暂无发送多个附件的需求
    ''')
    
    #参数解析
    def argParse():
        subject,content,destAddr,content_file,attachment=None,None,None,None,None
        '''
        如果参数很多,可以选择用argparse模块,argparse是更加完善、更加简单的参数解析工具,这里用getopt只是因为想试下getopt怎么用。
        getopt(args, shortopts, longopts = [])
        shortopts表示短项参数,longopts表示长项参数,前者使用'-'后者使用'--',需要后接具体参数的短项参数后需要加冒号':'标识,longopts则必须以=结尾,赋值时写不写等号无所谓因为默认是模糊匹配的。
        getopt的返回值分两部分,第一部分是所有配置项和其值的list,类似[(opt1,val1),(opt2,val2),...],第二部分是未知的多余参数,我们只需要在第一部分的list取参数即可。
        第二部分一般无需关注,因为我们会使用getopt.GetoptError直接过滤掉这些参数(即直接报option xxx not recognized)。
        '''
        try:
            sopts, lopts = getopt.getopt(sys.argv[1:],"hs:c:d:",["help","content-file=","attach="])
        except getopt.GetoptError as e:
    	    print("GetoptError:")
    	    print(e)
            sys.exit(-1)
        for opt,arg in sopts:
    	    if opt == '-s':
    	        subject=arg
    	    elif opt == '-c':
    	        content=arg
    	    elif opt == '-d':
    	        destAddr=arg
    	    elif opt == '--attach':
    	        attachment=arg
    	    elif opt == '--content-file':
    	        content_file=arg
    	    elif opt == '--attach':
    	        attachment=arg
    	    else:
    	        usage()
    	        sys.exit(-1)
        #subject,destAddr必须不能为空
        if not subject or not destAddr:
    	    usage()
    	    print("Error: subject and destination must not be null!")
    	    sys.exit(-1)
        #处理正文文件,如果存在正文文件,那么忽略-c参数,以文件内容为邮件正文
        if content_file and os.path.exists(content_file):
    	    try:
    	        with open(content_file) as f1:
    	            content=f1.read()
    	    except:
    	        print("Can't open or read the content file!")
    	        exit(-1)
        else:
    	    pass
        return {'s':subject,'c':content,'d':destAddr,'a':attachment,}
    
    #发送邮件
    def main():	
        opts=argParse()
        subject,content,dest,attach=opts['s'],opts['c'],opts['d'],opts['a']
        #通用第三方smtp服务器账号密码
        smtp_server = 'smtp.163.com'
        from_addr = '你的163发件箱'
        password = '你的163发件箱密码'
        to_addr = list(dest.split(","))
    
        msg = MIMEMultipart()
        msg['From'] = from_addr
        msg['To'] = ','.join(to_addr)
        msg['Subject'] = subject
        msg.attach(MIMEText(content, 'plain', 'utf-8'))
    
        #处理附件
        if attach and os.path.exists(attach):
    	    try:
    	        with open(attach) as f2:
    		        mime=f2.read()
    		        #目前懒的再写多个附件了,因此只支持一个附件
    		        attach1=MIMEApplication(mime)
    		        attach1.add_header('Content-Disposition','attachment',filename=attach)
    		        msg.attach(attach1)
    	    except:
    	        print("Can't open or read the attach file!")
    	        exit(-1)
        else:
    	    pass
     
        server = smtplib.SMTP_SSL(smtp_server, 465) #如果使用的25端口的非加密通道,那么使用SMTP方法替换SMTP_SSL
        server.set_debuglevel(1)
        server.login(from_addr, password)
        server.sendmail(from_addr, to_addr, msg.as_string())
        server.quit()
    
    if __name__=='__main__':
        main()

    三、更改权限后就可以在安装了python的服务器上发送邮件啦(一般服务器都自带python2版本)。

    例如:

    [root@python leo]# chmod 755 SendMail.py
    [root@python leo]# ./SendMail.py -s "邮件标题" -c "邮件正文" -d "xxx@qq.com" --content-file mail.txt 
  • 相关阅读:
    百度编辑器 Ueditor使用记录
    JS实现继承的几种方式
    IOS 浏览器上设置overflow: auto 不可滚动
    throw new Error('Cyclic dependency' + nodeRep)
    如何理解springaop
    SQL连接的分类
    Eclipse创建Maven-Web项目及解决 jre版本和web.xml版本问题
    SQL的几种连接:内连接、左联接、右连接、全连接、交叉连接
    Centos7下面安装eclipse
    Centos7 下编译 Openjdk8
  • 原文地址:https://www.cnblogs.com/leohahah/p/10775078.html
Copyright © 2011-2022 走看看