pyledriver/gmail.py

77 lines
2.3 KiB
Python
Raw Normal View History

2016-12-30 02:51:56 -05:00
import logging, time
from config import configFile
from exceptionThreading import async
2016-12-30 02:51:56 -05:00
from smtplib import SMTP
from datetime import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
2017-05-31 00:26:28 -04:00
logger = logging.getLogger(__name__)
2016-12-30 02:51:56 -05:00
gmail = configFile['gmail']
2016-12-30 02:51:56 -05:00
def _getNextDate():
2016-12-30 02:51:56 -05:00
m = datetime.now().month + 1
y = datetime.now().year
y = y + 1 if m > 12 else y
return datetime(year=y, month=m%12, day=1, hour=12, minute=0)
@async(daemon=True)
def _scheduleAction(action):
2016-12-30 02:51:56 -05:00
while 1:
nextDate = _getNextDate()
2016-12-30 02:51:56 -05:00
sleepTime = nextDate - datetime.today()
2017-05-31 00:26:28 -04:00
logger.info('Next monthly test scheduled at %s (%s)', nextDate, sleepTime)
2016-12-30 02:51:56 -05:00
time.sleep(sleepTime.days * 86400 + sleepTime.seconds)
action()
@async(daemon=False)
def _sendToGmail(username, passwd, recipiantList, subject, body, server='smtp.gmail.com', port=587):
2016-12-30 02:51:56 -05:00
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = username
msg['To'] = ', '.join(recipiantList)
2016-12-30 02:51:56 -05:00
msg.attach(MIMEText(body, 'plain'))
s = SMTP(server, port)
2016-12-30 02:51:56 -05:00
s.starttls()
s.login(username, passwd)
2016-12-30 02:51:56 -05:00
s.send_message(msg)
s.quit()
def monthlyTest():
subject = 'harrison4hegemon - automated monthly test'
body = 'this is an automated message - please do not reply\n\nin the future this may have useful information'
2017-06-02 00:12:05 -04:00
_sendToGmail(gmail['username'], gmail['passwd'], gmail['recipientList'], subject, body)
2017-05-31 00:26:28 -04:00
logger.debug('Sending monthly test to email list')
2016-12-30 02:51:56 -05:00
def intruderAlert():
2017-06-02 00:12:05 -04:00
pass
2016-12-30 02:51:56 -05:00
subject = 'harrison4hegemon - intruder detected'
body = 'intruder detected - alarm was tripped on ' + time.strftime("%H:%M:%S - %d/%m/%Y")
2017-06-02 00:12:05 -04:00
_sendToGmail(gmail['username'], gmail['passwd'], gmail['recipientList'], subject, body)
2017-05-31 00:26:28 -04:00
logger.info('intruder detected')
logger.debug('Sending intruder alert to email list')
class GmailHandler(logging.Handler):
'''
Logging handler that sends records to gmail. This is almost like the
SMTPHandler except that the username and fromaddr are the same and
credentials are mandatory
'''
def __init__(self, username, passwd, recipientList, subject):
super().__init__()
self.username = username
self.passwd = passwd
self.recipientList = recipientList
self.subject = subject
def emit(self, record):
try:
_sendToGmail(self.username, self.passwd, self.recipientList,
self.subject, self.format(record))
except:
self.handleError(record)
2016-12-30 02:51:56 -05:00
_scheduleAction(monthlyTest)