-
Notifications
You must be signed in to change notification settings - Fork 4
/
flows_daily_candidate_email.py
165 lines (142 loc) · 5.55 KB
/
flows_daily_candidate_email.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# TODO: Imported as is/was from zion:/usr/users/kasoc/flows/ (zion.phys.au.dk: 10.28.0.245),
# so will need modifications
import argparse
import logging
import os
import datetime
#import getpass
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from astropy.coordinates import Angle
import sys
if '/usr/users/kasoc/Preprocessing/' not in sys.path:
sys.path.insert(0, '/usr/users/kasoc/Preprocessing/')
#sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), 'flows')))
from kasocutil import psql_connect # 2024-12-19 erik: no trace of this module in '/usr/users/kasoc' ...
#import flows
if __name__ == '__main__':
# Parse command line arguments:
parser = argparse.ArgumentParser(description='Send out candidate e-mails.')
parser.add_argument('-d', '--debug', help='Print debug messages.', action='store_true')
parser.add_argument('-q', '--quiet', help='Only report warnings and errors.', action='store_true')
args = parser.parse_args()
# Set logging level:
logging_level = logging.INFO
if args.quiet:
logging_level = logging.WARNING
elif args.debug:
logging_level = logging.DEBUG
# Setup logging:
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console = logging.StreamHandler()
console.setFormatter(formatter)
logger = logging.getLogger(__name__)
if not logger.hasHandlers():
logger.addHandler(console)
logger.setLevel(logging_level)
#passwd = getpass.getpass('Password: ')
with psql_connect('flows_notifier') as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM flows.targets WHERE target_status='candidate' AND included_in_email IS NULL ORDER BY target_name;")
results = cursor.fetchall()
if results:
logger.info("%d new candidates found.", len(results))
now = datetime.datetime.utcnow()
html = """\
<html>
<head>
<style type="text/css">
body {
font-family: "Open Sans", Verdana, Arial, sans-serif;
}
table.tablesorter {
background-color: #CDCDCD;
margin: 10px 0pt 15px;
width: 100%;
text-align: left;
}
table.tablesorter thead tr th, table.tablesorter tfoot tr th {
background-color: #e6EEEE;
border: 1px solid #FFF;
padding: 4px;
}
table.tablesorter thead tr .header {
background-image: url(/css/tablesorter/bg.gif);
background-repeat: no-repeat;
background-position: center right;
cursor: pointer;
}
table.tablesorter tbody td {
color: Black;
padding: 4px;
background-color: #FFF;
vertical-align: top;
}
p.footer {
font-size: smaller;
}
</style>
</head>
<body>"""
html += "<p>Flows, Aarhus University<br>\n" + now.strftime('%d %B %Y %H:%M') + "</p>";
html += "<p>Dear Flows members,</p>"
html += "<p>The following candidates have been automatically added to the Flows candidate list:</p>"
html += '<table class="tablesorter" style="width:100%;"><thead>'
html += "<tr>"
html += '<th style="width:10%;">Candidate</th>'
html += '<th style="width:18%;">RA</th>'
html += '<th style="width:18%;">Dec</th>'
html += '<th style="width:18%;">Redshift</th>'
html += '<th style="width:18%;">Discovery mag.</th>'
html += '<th style="width:18%;">Discovery date</th>'
html += "</tr>"
html += "</thead><tbody>"
for row in results:
print(row)
html += "<tr>"
html += '<td><a href="https://flows.phys.au.dk/candidates/{0:d}" target="_blank">{1:s}</a></td>'.format(row['targetid'], row['target_name'])
html += '<td style="text-align:right">{0}</td>'.format(Angle(row['ra']/15, unit='deg').to_string(sep=':', precision=1))
html += '<td style="text-align:right">{0}</td>'.format(Angle(row['decl'], unit='deg').to_string(sep=':', alwayssign=True, precision=1))
html += '<td style="text-align:right">{0:.3f}</td>'.format(row['redshift'])
if row['discovery_mag'] is None:
html += '<td> </td>'
else:
html += '<td style="text-align:right">{0:.2f}</td>'.format(row['discovery_mag'])
if row['discovery_date'] is None:
html += '<td> </td>'
else:
html += '<td style="text-align:right">{0}</td>'.format(row['discovery_date'].strftime('%Y-%m-%d %H:%M'))
html += "</tr>\n"
html += "</tbody></table>"
html += "<p>Best regards,<br>The Flows Team</p>"
#html += "<p class=\"footer\">If you no longer wish to receive these e-mails, go to 'My Account' on the TASOC website to disable e-mail notifications about upcoming events.</p>"
html += "</body>"
html += "</html>"
#recipients = ['[email protected]']
recipients = ['[email protected]']
# Send an e-mail that the file is ready for download:
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "New Flows candidates"
msg['From'] = "Flows <[email protected]>"
msg['To'] = ', '.join(recipients)
#msg.attach(MIMEText(text, 'plain'))
msg.attach(MIMEText(html, 'html'))
# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(msg['From'], recipients, msg.as_string())
s.quit()
logger.info("E-mail sent!")
for row in results:
cursor.execute("UPDATE flows.targets SET included_in_email=%s WHERE targetid=%s;", [now, row['targetid']])
conn.commit()
logger.info("Targets updated.")
else:
logger.warning("No new candidates to broadcast")
cursor.close()
logger.info("Done.")