# -*- 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()

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=''

line_num=0
for line in files_Lst[:100]:
    line_num+=1  
    filename=line['filename']
    filemt=datetime.datetime.fromtimestamp(line['modify_ts']).isoformat()[:19]
    line_str='%3d\t%s\t\t%s\n' % (line_num, 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())


