send emails to users when ip doesn't match
[0tDNS.git] / src / send_emails.py
blobbbbd7b0eee36ab103d7bd20dadab2f506c76f04d
1 #!/usr/bin/python3
3 from time import gmtime, strftime, time
5 import smtplib
7 from ztdnslib import start_db_connection, get_ztdns_config
9 def sendMail(to, subject, content):
11 email = 'FILL THIS FIELD'
12 password = 'FILL THIS FIELD'
13 message = 'Subject: {}\n\n{}'.format(subject, content)
14 mail = smtplib.SMTP('smtp.gmail.com',587)
15 mail.ehlo()
16 mail.starttls()
17 mail.login(email,password)
18 mail.sendmail('zerotdns@gmail.com',to, message)
19 mail.close()
22 config = get_ztdns_config()
23 if config['send_user_emails'] not in [True, 'yes']:
24 print('Sending emails disabled in config - exiting')
25 exit()
27 selectEmailsThatFailured = '''select distinct email from auth_user au
28 inner join user_side_subscription uss on au.id = uss.user_id
29 inner join user_side_service usservice on uss.service_id = usservice.id
30 inner join user_side_responses usr on usservice.id = usr.service_id
31 inner join user_side_response usr1 on usr.id = usr1.responses_id
32 where usr.result like 'successful' and usr1.returned_ip != usservice."IP" and
33 usr.date = TIMESTAMP WITH TIME ZONE %s'''
35 connection = start_db_connection(config)
36 cursor = connection.cursor()
38 seconds = time()
39 seconds_hour_ago = seconds - 3600
40 timestamp_hour_ago = strftime('%Y-%m-%d %H:00%z', gmtime(seconds_hour_ago))
42 cursor.execute(selectEmailsThatFailured, (timestamp_hour_ago,))
44 content = 'Uwaga, DNS odpowiedziaƂ niepoprawnym adresem!'
45 # to = 'example@site.com'
46 subject = '0tdns alert'
48 for row in cursor.fetchall():
49 to = row[0]
50 if (to != ""):
51 sendMail(to, subject, content)
53 cursor.close()
54 connection.close()