-
Notifications
You must be signed in to change notification settings - Fork 0
/
saltemail.py
223 lines (190 loc) · 8.49 KB
/
saltemail.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
################################# LICENSE ##################################
# Copyright (c) 2009, South African Astronomical Observatory (SAAO) #
# All rights reserved. #
# #
# Redistribution and use in source and binary forms, with or without #
# modification, are permitted provided that the following conditions #
# are met: #
# #
# * Redistributions of source code must retain the above copyright #
# notice, this list of conditions and the following disclaimer. #
# * Redistributions in binary form must reproduce the above copyright #
# notice, this list of conditions and the following disclaimer #
# in the documentation and/or other materials provided with the #
# distribution. #
# * Neither the name of the South African Astronomical Observatory #
# (SAAO) nor the names of its contributors may be used to endorse #
# or promote products derived from this software without specific #
# prior written permission. #
# #
# THIS SOFTWARE IS PROVIDED BY THE SAAO ''AS IS'' AND ANY EXPRESS OR #
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED #
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE #
# DISCLAIMED. IN NO EVENT SHALL THE SAAO BE LIABLE FOR ANY #
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL #
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS #
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) #
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, #
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN #
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #
# POSSIBILITY OF SUCH DAMAGE. #
############################################################################
#!/usr/bin/env python
# Author Version Date
# -----------------------------------------------
# Martin Still (SAAO) 0.2 17 Aug 2007
# S M Crawford (SAAO) 0.3 01 Feb 2007
# email PI with 'data-is-ready' notification letter
# v0.3:
# --updated to include mysql query
# --updated to look for propcode and not PI name
from pyraf import iraf
import smtplib, string
from email.mime.text import MIMEText
import saltsafekey as saltkey
import saltsafeio as saltio
import saltsafemysql as saltmysql
import saltsafestring as saltstring
from saltsafelog import logging, history
from salterror import SaltError, SaltIOError
debug=True
# -----------------------------------------------------------
# core routine
def saltemail(propcode, obsdate,readme,server='mail.saao.ac.za',username='', password='',
bcc='',sdbhost='sdb.saao',sdbname='sdb',sdbuser='pipeline',
logfile='salt.log',verbose=True):
"""For a given date, look into the database for observations made on that
date. If propcode='all' send an email to all of the PIs that had data taken on that date.
If propcode gives a specific proposal, only send emails to that PI.
"""
# set up
sender = 'sa@salt.ac.za'
bcclist = bcc.split(',')
date_obss = []
propids = []
pis = []
pids = []
email = []
with logging(logfile,debug) as log:
#set up the proposal list
pids = saltio.argunpack('propcode',propcode)
#check to see if the argument is defined
saltio.argdefined('obsdate',obsdate)
# check readme file exists
saltio.fileexists(readme)
#connect to the email server
try:
smtp = smtplib.SMTP()
smtp.connect(server)
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
except Exception, e:
message = 'Cannot connect to %s because %s' % (server, e)
log.error(message)
try:
smtp.login(username,password)
except Exception, e:
message = 'Cannot login to %s as %s because %s' % (server, username, e)
log.error(message)
# log into the mysql data base and download a list of proposal codes
sdb=saltmysql.connectdb(sdbhost, sdbname, sdbuser, password)
select='distinct Proposal_Code'
table='FileData join ProposalCode using (ProposalCode_Id)'
logic="FileName like '%" + obsdate + "%'"
records=saltmysql.select(sdb, select, table, logic)
if len(records)<1:
msg="No observations available for %s" % obsdate
log.warning(msg)
return
else:
for p in records:
propids.append(p[0])
#clean the proposal list
print pids, propids
try:
pids=saltio.cleanpropcode(pids, propids)
pids=saltio.removebadpids(pids)
pids=saltio.removeengineeringpids(pids)
except SaltIOError:
msg="No notifications necessary for %s" % obsdate
log.warning
return
#loop through each of the pids and send the email
for pid in pids:
propinfo=findpropinfo(pid, sdb)
if propinfo:
for pi, email in zip(propinfo[pid][0], propinfo[pid][1]):
letter=saltio.openascii(readme,'r')
msg=letter.read()
msg=msg.replace('yourname',pi)
msg=msg.replace('YYYY-INST-PID',pid.upper())
msg=msg.replace('yyyymmdd',obsdate)
saltio.closeascii(letter)
#set up the message to be sent
recip = []
#uncomment the following lines if you just want to send the email
#to yourself
#email='crawford@saao.ac.za'
#bcclist=[]
recip.append(email)
for bccobj in bcclist:
recip.append(bccobj)
msg = MIMEText(msg)
msg['Subject'] = 'SALT data available for download for %s' % pid.upper()
msg['From'] = sender
msg['To'] = email
msg['bcc'] = bcc
try:
smtp.sendmail(sender,recip,msg.as_string())
pass
except:
message = 'Failed to send email to ' + pi
log.error(message)
message='Email sent to %s at %s' % (pi, email)
log.message(message)
#disconnect from the email server
try:
smtp.quit()
except:
message = 'Cannot disconnect from email server ' + server
log.error(message)
def findpropinfo(pid,sdb):
"""query the Sdb server and determine the email and surname
for the contact information for the proposal
return a dictionary with Surname,Email
"""
propinfo={}
#setup the the query
state_select='c.Proposal_Code,c.Proposal_Code,i2.Surname,i2.Email'
state_from='''
Investigator as i join PiptUser using (PiptUser_Id) join Investigator as i2 on (PiptUser.Investigator_Id=i2.Investigator_Id),
ProposalCode as c
join ProposalContact as pc using (ProposalCode_Id) '''
state_logic="i.Investigator_Id=pc.Contact_ID and pc.ProposalCode_ID=c.ProposalCode_ID and c.Proposal_Code='%s'" %pid
# left over by intersting way to call it: ORDER BY pr.Proposal_ID DESC" % pid
record=saltmysql.select(sdb,state_select,state_from,state_logic)
if len(record)<1:
message = pid + ' is not in the Science database'
raise SaltError(message)
elif len(record)==1:
surname=[record[0][2]]
email=[record[0][3]]
propinfo[pid]=(surname,email)
else:
prop_id=-1
surname=[]
email=[]
for entry in record:
if entry[0] > prop_id:
prop_id=entry[0]
prop_code=entry[1]
surname.append(entry[2])
email.append(entry[3])
propinfo[pid]=(surname,email)
return propinfo
# -----------------------------------------------------------
# main code
if not iraf.deftask('saltemail'):
parfile = iraf.osfn("pipetools$saltemail.par")
t = iraf.IrafTaskFactory(taskname="saltemail",value=parfile,function=saltemail, pkgname='pipetools')