• [linux & python] linux下基于python自动定时发送邮件附件


    linux下基于python自动定时发送邮件附件

    暂时接手一个离职前端实习生的工作,昨天第一次对接产品,跟我说每天晚上要给她发送一个当天的报表。
    每天?excuse me?每天?开什么国际玩笑。每天干同一个工作,这要不给整成auto的,还怎么自称屌丝程序猴。今天果断研究了下自动发送邮件。
    原理不懂,只实现功能

    主要是两部分
    python自动发送邮件, 基于SMTP协议,使用email和smtplib库
    linux定时执行, cron

    AUTO-Email python code

    功能描述:
    将一个以日期格式命名(yyyymmdd)的文件夹压缩zip包,通过邮件附件形式发送指定邮箱。

    #!/bin/env python
    # -*- coding: utf-8 -*-
    
    import datetime
    import smtplib
    import os,sys
    from email import Encoders  
    from email.mime.text import MIMEText
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from optparse import OptionParser
    
    HOME=sys.path[0]
    #sender name and password
    sendername="haha"						#your email name
    sendername_all="haha@hehe.com"			#your email
    senderpass="wonazhidao"					#email password
    #list of all receiver (include cc-receiver)
    receiverlist=["haha1@hehe.com","haha2@hehe.com"]		#收件人
    receivertmplist=[]		
    receivercctmplist=[]									#抄送人
    
    #make a mail    
    mailall=MIMEMultipart()
    
    today=str(datetime.date.today()).replace('-','')		#今天日期
    
    mailcontent="haha"										
    mailall.attach(MIMEText(mailcontent,'plain','utf-8'))	#邮件正文内容,类型是plain, or html(复杂)
    title=today+" Data report"
    #today=os.path.join(HOME,today)
    attfilePath=today+'.zip'
    
    if os.path.exists(today):
        sys_cmd="zip -r %s %s"%(attfilePath,today)
        os.system(sys_cmd)
        if not os.path.isfile(attfilePath):
            print("no zip file")
    else:
        print("no folder")
    
    #添加zip邮件附件(通用其他文件格式)
    if os.path.isfile(attfilePath) and os.path.exists(today):
        with open(attfilePath,'rb') as f:
            contype = 'application/octet-stream'
            maintype,subtype=contype.split('/',1)
            attfile=MIMEBase(maintype,subtype)
            attfile.set_payload(f.read())
            Encoders.encode_base64(attfile)			#Base64编码(为啥不知道) 
            attfile.add_header('Content-Disposition','attachment',filename = attfilePath)	#头信息,貌似并不是附件名称
            print("attach file prepared!")
            mailall.attach(attfile)
    else:
        title="some wrong!!!"
        print(title)
    
    #title,sender,receiver,cc-receiver,
    #邮件基本信息,主题,发送人,收件人,抄送人
    mailall['Subject']=title    #options.title
    mailall['From']=sendername_all
    mailall['To']=str(receivertmplist)
    if len(receivercctmplist) !=0:
        mailall['CC']=str(receivercctmplist)
    
    
    #get the text of mailall
    fullmailtext=mailall.as_string()
    print("prepare fullmailtext ok.")
    #mailconnect = smtplib.SMTP(options.server)
    mailconnect = smtplib.SMTP("smtp.126.com")		#email server,port default 25
    try:
        mailconnect.login(sendername,senderpass)
    except Exception as e:
        print("error when connect the smtpserver with the given username and password !")
        print(e)
    
    print("connect ok!")
    
    try:
        mailconnect.sendmail(sendername_all, receiverlist, fullmailtext)
    except Exception as e:
        print("error while sending the email!")
    finally:
        mailconnect.quit()
    
    print('email to '+str(receiverlist)+' over.')
    
    

    定时执行cron

    cron是linux下的定时执行工具,可以在无需人工干预的情况下运行作业。

    root或su下操作。
    首先查看cron是否启动。

    service cron status		//查看cron状态
    service crond start 	//启动服务
    service crond stop 		//关闭服务
    service crond restart 	//重启服务
    service crond reload 	//重新载入配置
    

    然后修改crontab.

    crontab –e : 修改 crontab 文件,如果文件不存在会自动创建 
    crontab –l : 显示 crontab 文件
    
    #crontab书写格式:
    minute(00-59) hour(00-24) day-of-month(01-31) month-of-year(01-12) day-of-week(0-6,0:Sunday) commands
    

    在crontab中写入需要执行的命令和时间,前五个域是指定命令执行时间,最后一个域是执行命令。每个域之间使用空格或者制表符分隔。

    除了数字还有几个特殊的符号:"*"、"/"和"-"、","
    *代表所有的取值范围内的数字
    "/"代表每的意思,"/5"表示每5个单位
    "-"代表从某个数字到某个数字
    ","分开几个离散的数字

    commands 注意
    文件要写绝对路径
    打印不会显示出来,在后台运行,做好重定向日志

    0 6 * * * echo "Good morning."					#6:00 every day
    15 */2 * * * echo "Good morning."				#每两个小时的第15分钟
    0 4 1 1 * echo "Good morning."					#1月1日4:00
    5,15,55 16,18 * * * echo "Good morning."		#每天16点、18点的5min、15min、55min执行
    

    小坑记录

    1. smtp时先确保机器是能够ping通邮箱服务器的。公司的开发机器居然ping不通自己的email server!真尴尬,第一反应是端口被封了,试了半天没改善。
    2. cron,在命令执行时,如果涉及到shell或者py文件,注意要给到完整绝对路径,否则会出问题。
    3. 在执行py文件前,可以先将其编译pyo文件,保密并且载入执行的效率会高,删掉.py,执行.pyo即可。
      python -O -m py_compile /path/to/需要生成.pyo的脚本.py

    Reference

    首推每个的第一个
    auto-email:
    http://blog.csdn.net/lifeiaidajia/article/details/8525259
    http://blog.csdn.net/kornberg_fresnel/article/details/51227761
    http://blog.sina.com.cn/s/blog_78c913e30102x6i5.html
    http://wjpingok.blog.51cto.com/5374697/1737182
    cron:
    http://www.cnblogs.com/kaituorensheng/p/4494321.html
    http://blog.csdn.net/xionglangs/article/details/52913351

  • 相关阅读:
    解决genemotion模拟器冲突导致的Android Studio无法启动ADB的问题
    Google Chrome Resize Plugin
    IntelliJ IDEA + Maven创建Java Web项目
    iOS开发
    Java对象和XML的相互转换化
    使用SpringMVC的@Validated注解验证的实现
    Spring @Validated 使用
    @validated注解实现
    springmvc的@Validated注解使用
    C#调用C++编写的DLL
  • 原文地址:https://www.cnblogs.com/zhanxiage1994/p/7774934.html
Copyright © 2020-2023  润新知