# -*- coding: utf-8 -*-
"""
Created on Fri Feb  2 17:26:50 2018

@author: hanye
"""

import os
import smtplib
from email.message import EmailMessage
import datetime
import time

os.chdir('/home/hanye/project_data/Python/Projects/proj-short-videos/write-data-into-es/log')
files=os.listdir()

while True:
    now=datetime.datetime.now()
    if (now.year==2018 and now.month==2 and now.day in [3, 4] and now.hour in [2, 9, 11, 12, 18, 21]):
        files_Lst=[]
        for ff in files:
            mt=os.path.getmtime(ff)
            filed={'filename':ff, 'modify_ts':mt}
            files_Lst.append(filed)
        
        files_Lst.sort(key=lambda d: d['modify_ts'], reverse=True)
        email_msg_body=''
        for line in files_Lst[:100]:
            filename=line['filename']
            filemt=datetime.datetime.fromtimestamp(line['modify_ts']).isoformat()[:19]
            line_str=filename+' '+filemt
            
            email_msg_body+=line_str+'\n'
        
        email_msg_suffix=('\n\n\n'
                          +'-'*80+'\n'
                          +'这是自动发送的邮件，可以不用回复。\n'
                          +'This is an automatically sent message. You do NOT need to reply.\n')
        email_msg_body+=email_msg_suffix
        
        
        csm_mail_service='mail.csm.com.cn'
        sender='ccr_maintain@csm.com.cn'
        receiver=['hanye@csm.com.cn', 'yeahan@outlook.com']
        email_subj='check on log directory %s' % datetime.datetime.now().isoformat()[:19]
        
        email_msg=EmailMessage()
        email_msg.set_content(email_msg_body)
        email_msg['Subject']=email_subj
        email_msg['From']=sender
        email_msg['to']=receiver
        
        try:
            server=smtplib.SMTP(host=csm_mail_service)
            server.send_message(email_msg)
            server.quit()
            print('Successfully sent email to %s' % receiver,
                  datetime.datetime.now())            
            print('email_msg:\n', email_msg)
        
        except:
            print('Failed to connect email server.', datetime.datetime.now())
        
        time.sleep(60*60)
        
    if now>datetime.datetime(2018,2,4,23):
        break

    time.sleep(60)
