forked from Hydrosys4/Master
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathemailmod.py
311 lines (241 loc) · 7.59 KB
/
emailmod.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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import logging
import datetime
import hardwaremod
import os
import subprocess
import emaildbmod
import networkmod
import sensordbmod
import actuatordbmod
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
logger = logging.getLogger("hydrosys4."+__name__)
# GET path ---------------------------------------------
global MYPATH
print "path ",hardwaremod.get_path()
MYPATH=hardwaremod.get_path()
global IPEXTERNALSENT
IPEXTERNALSENT=""
def send_email(user, pwd, recipient, subject, body):
gmail_user = user
gmail_pwd = pwd
FROM = user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd)
server.sendmail(FROM, TO, message)
server.quit()
print 'successfully sent the mail'
except:
print "failed to send mail"
def create_htmlopen():
html = """\
<html>
<head>
</head>
<body>
"""
return html
def create_htmlclose():
html = """\
</body>
</html>
"""
return html
def create_htmlintro(intromessage):
html = """\
<h3> """ + intromessage + """</h3>
"""
return html
def create_htmlbody(bodytextlist):
# the input should be a list
html = """\
<p></p>
"""
for textrow in bodytextlist:
html = html + """\
<p> """ + textrow + """</p>
"""
return html
def create_htmladdresses(address1, address2, port):
address1=address1+":"+port
address2=address2+":"+port
html = """\
<h3>Below the links for System connection:</h3>
<p></p>
<a href="http://""" + address1 + """">link for remote connection </a>
<p></p>
<p></p>
<a href="http://""" + address2 + """">link for local connection </a>
<p></p>
<p></p>
"""
return html
def create_htmlmatrix(matrixinfo):
htmlopen = """<table style="width:100%!important" cellpadding="2" cellspacing="1">"""
htmlheader="""<tr>"""
for header in matrixinfo[0]:
htmlheader = htmlheader+ """<th align="center" style="background: #81BEF7; border:0px !important;">"""+ header +"""</th> """
htmlheader = htmlheader+ """</tr> """
htmltable=""
for row in matrixinfo[1:]:
htmltable=htmltable + """<tr> """
for element in row:
htmltable = htmltable+ """<td align="center" style="background: #2E64FE; border:0px !important;">"""+ element +"""</td> """
htmltable = htmltable+ """</tr> """
htmlclose = """ </table>"""
html=htmlopen+htmlheader+htmltable+htmlclose
return html
def send_email_html(user, pwd, recipient, subject, html, showpicture):
# me == my email address
# you == recipient's email address
gmail_user = user
gmail_pwd = pwd
me = user
you=[]
for address in recipient.split(";"):
you.append(address.strip())
print " Sending mail to : ", recipient
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = me
msg['To'] =", ".join(you)
#msg.preamble = 'Our family reunion'
# Create the body of the message HTML version
# Record the MIME t
part1 = MIMEText(html, 'html')
msg.attach(part1)
if showpicture:
#retrieve last picture ------------------------------------
global MYPATH
photolist=hardwaremod.photolist(MYPATH)
imgfiles=[]
if photolist:
referencestr=photolist[0][0].split(",")[0]
for items in photolist:
if referencestr in items[0]:
folderpath=os.path.join(MYPATH, "static")
folderpath=os.path.join(folderpath, items[0])
imgfiles.append(folderpath)
for filename in imgfiles:
# Open the files in binary mode. Let the MIMEImage class automatically
# guess the specific image type.
print "filename " , filename
fp = open(filename, 'rb')
img = MIMEImage(fp.read())
fp.close()
picturename=os.path.basename(filename)
img.add_header('Content-Disposition','attachment; filename="%s"' % picturename)
msg.attach(img)
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd)
server.sendmail(me, you, msg.as_string())
server.quit()
print 'successfully sent the mail'
logger.info('mail sent succesfully ')
return True
except:
logger.error('failed to send mail')
print "failed to send mail"
return False
def send_email_main(address,title,cmd,mailtype,intromessage,bodytextlist=[]):
# mailtype option
# "report"
# "alert"
if mailtype=="report":
starttitle="Report:"
showtable=True
showpicture=True
showlink=True
elif mailtype=="alert":
starttitle="Alert:"
showtable=False
showpicture=False
showlink=True
currentdate=datetime.datetime.now().strftime("%y-%m-%d,%H:%M")
# got credentials here !
user=emaildbmod.getaddress()
pwd=emaildbmod.getpassword()
recipient=address
# check IP address
iplocal=networkmod.get_local_ip()
ipext=networkmod.EXTERNALIPADDR
if ipext=="":
logger.info('Stored external IP address is empty, try to get it from network')
ipext=networkmod.get_external_ip()
print "Try to send mail"
# subject of the mail
subject=starttitle +" " + title + " " + currentdate
htmlbody=create_htmlopen()
htmlbody=htmlbody+create_htmlintro(intromessage)+create_htmlbody(bodytextlist)
if showlink:
if ipext=="":
print "No external IP address available"
logger.error('Unable to get external IP address')
else:
port=str(networkmod.PUBLICPORT)
if cmd=="mail+info+link":
htmlbody=htmlbody+create_htmladdresses(ipext, iplocal, port)
if showtable:
# table with information
matrixinfo=sensordbmod.sensorsysinfomatrix()
htmlbody=htmlbody+create_htmlmatrix(matrixinfo)
matrixinfo=actuatordbmod.sensorsysinfomatrix()
htmlbody=htmlbody+create_htmlmatrix(matrixinfo)
htmlbody=htmlbody+create_htmlclose()
issent=send_email_html(user, pwd, recipient, subject, htmlbody, showpicture)
if (issent) and (showlink) and (ipext!=""):
global IPEXTERNALSENT
IPEXTERNALSENT=ipext
return issent
def sendallmail(mailtype,intromessage,bodytextlist=[]):
usedfor="mailcontrol"
hwnamelist=hardwaremod.searchdatalist(hardwaremod.HW_FUNC_USEDFOR,usedfor,hardwaremod.HW_INFO_NAME)
for hwname in hwnamelist:
sendmail(hwname,mailtype,intromessage,bodytextlist)
def sendmail(hwname,mailtype,intromessage,bodytextlist=[]):
address=hardwaremod.searchdata(hardwaremod.HW_INFO_NAME,hwname,hardwaremod.HW_CTRL_MAILADDR)
if not address=="":
print "mail recipient ", address
title=hardwaremod.searchdata(hardwaremod.HW_INFO_NAME,hwname,hardwaremod.HW_CTRL_MAILTITLE)
print "mail title " , title
cmd=hardwaremod.searchdata(hardwaremod.HW_INFO_NAME,hwname,hardwaremod.HW_CTRL_CMD)
print "mail type " , cmd
issent=send_email_main(address,title,cmd,mailtype,intromessage,bodytextlist)
return issent
else:
print "No address specified"
logger.error('No address specified')
return False
if __name__ == '__main__':
"""
prova email
"""
currentdate=datetime.datetime.now().strftime("%y-%m-%d,%H:%M")
user="[email protected]"
pwd="hydrosystem"
recipient="[email protected]"
subject="Today update " + currentdate
body="sono il testo prova 2"
#send_email(user, pwd, recipient, subject, body)
ipext=networkmod.get_external_ip()
iplocal=networkmod.get_local_ip()
htmlbody=create_html(ipext, iplocal, "5012")
print htmlbody
send_email_html(user, pwd, recipient, subject, htmlbody)