Эх сурвалжийг харах

HTML Email format. Config file now holds recipient addresses.

Miek Stagl 5 жил өмнө
parent
commit
3e426d60c3
3 өөрчлөгдсөн 78 нэмэгдсэн , 28 устгасан
  1. 31 10
      custom_email.py
  2. 39 14
      index.py
  3. 8 4
      landsearch.conf

+ 31 - 10
custom_email.py

@@ -1,31 +1,52 @@
 #!/usr/bin/python3
 
 import smtplib, ssl
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+import traceback
 
 
 class simplemail:
 
-    def __init__(self, subject, body, sendto=[], user='stagl.mike@gmail.com', password='cherokee2'):
+    def __init__(self, subject, body, sendto=[], user='stagl.mike@gmail.com', password='cherokee2', html=''):
         self.subject = subject
         self.body = body
         self.sendto = sendto
         self.user = user
         self.password = password
+        self.html = html
 
-    def sendmail(self):
-        email_text = """\
-From: %s
-To: %s
-Subject: %s
-
-%s
-""" % (self.user, self.sendto, self.subject, self.body)
+    def sendhtml(self):
+        msg = MIMEMultipart('alternative')
+        msg['Subject'] = self.subject
+        msg['To'] = ', '.join(self.sendto)
+        msg['From'] = self.user
+        msg.attach(MIMEText(self.html, 'html'))
 
         try:
             server_ssl = smtplib.SMTP_SSL('smtp.gmail.com', 465)
             server_ssl.ehlo()
             server_ssl.login(self.user, self.password)
-            server_ssl.sendmail(self.user, self.sendto, email_text)
+            server_ssl.sendmail(self.user, self.sendto, msg.as_string())
             server_ssl.close()
         except Exception as e:
             print('Something went wrong...', e)
+            # print(traceback.print_exc())
+
+#     def sendmail(self):
+#         email_text = """\
+# From: %s
+# To: %s
+# Subject: %s
+#
+# %s
+# """ % (self.user, self.sendto, self.subject, self.body)
+#
+#         try:
+#             server_ssl = smtplib.SMTP_SSL('smtp.gmail.com', 465)
+#             server_ssl.ehlo()
+#             server_ssl.login(self.user, self.password)
+#             server_ssl.sendmail(self.user, self.sendto, email_text)
+#             server_ssl.close()
+#         except Exception as e:
+#             print('Something went wrong...', e)

+ 39 - 14
index.py

@@ -9,6 +9,7 @@ from tabulate import tabulate
 from configparser import ConfigParser
 from os import path
 import logging
+from email.mime.text import MIMEText
 
 
 ### TO DO ###
@@ -57,6 +58,7 @@ class Parameters:
             self.config.read(self.file)
             self.search_params = self.config['Search']
             self.log_params = self.config['Logging']
+            self.email_params = self.config['Email']
         except Exception as err:
             print(err, "Using default search Parameters")
 
@@ -146,6 +148,7 @@ class MLSDATA:
         self.new_listings = []
         self.email = self.parameters.search_params.getboolean('email')
         self.live_google = self.parameters.search_params.getboolean('live_google')
+        self.recipients = self.parameters.email_params['recipients']
         print('Email  ' + str(self.email))
 
     def stringbuilder(self, search: Search, county):
@@ -422,18 +425,25 @@ class MLSDATA:
         logging.info(str(len(self.new_listings)) + " new listings found.")
 
     def email_results(self):
-        global mymail
-        sendto = ['stagl.mike@gmail.com', 'M_Stagl@hotmail.com']
+        global mymail, html
+        html = ''
+        # sendto = ['M_Stagl@hotmail.com', 'stagl.mike@gmail.com']
+        sendto = self.recipients.split(',')
+        # print(type(self.recipients))
+        # print(type(sendto))
         if self.email:
             ''' Send some kind of email! '''
             # If there are new listings, populate email ##
             if len(self.new_listings) > 0:
                 body = ''
                 data = []
+                html = '<html><head></head><body>'
+                html += '<p>Daily Real Estate Search Report.</p>'
+                html += '<p>The following properties have been found which may be of interest:</p>'
+                html += '<table>'
                 subj = str(len(self.new_listings)) + " New Real Estate Listings for " + str(datetime.date.today())
                 for listing in self.new_listings:
                     row = []
-                    body += listing.MLS + " | " + listing.address + " | " + listing.acres + " | " + listing.price + " | " + listing.link + "\n"
                     row.append(listing.MLS)
                     row.append(listing.address)
                     row.append('{:0,.2f}'.format(float(listing.acres)))
@@ -442,22 +452,37 @@ class MLSDATA:
                     row.append(listing.time_to_school / 60 if hasattr(listing, 'time_to_school') else 'NA')
                     row.append(listing.link)
                     data.append(row)
-                    body = """\
-                      Daily Real Estate Search Report\n
-                      The following properties have been found which may be of interest.\n
-                      """
-                    results = tabulate(data,
-                                       headers=['MLS', 'Address', 'Acres', 'sqft', 'Price', 'Time to School', 'link'])
-                    body += results
-
-                    mymail = custom_email.simplemail(subj, body, sendto)
+                    html += '<tr><td colspan=100%><hr></td></tr>'
+                    html += '<tr><th>MLS</th><td>' + listing.MLS + '</td></tr>'
+                    html += '<tr><th>Address</th><td>' + listing.address + '</td></tr>'
+                    html += '<tr><th>Acres</th><td>' + '{:0,.2f}'.format(float(listing.acres)) + '</td></tr>'
+                    html += '<tr><th>Time To School</th><td>' + (listing.time_to_school/60 if hasattr(listing, 'time_to_school') else 'NA') + '</td></tr>'
+                    html += '<tr><th>Price</th><td>' + '${:0,.0f}'.format(int(listing.price)) + '</td></tr>'
+                    html += '<tr><th>Link</th><td><a href=' + listing.link + '>Link</a></td></tr>'
+                    body = """Daily Real Estate Search Report.\n
+The following properties have been found which may be of interest.\n
+"""
+                results = tabulate(data, headers=['MLS', 'Address', 'Acres', 'sqft', 'Price', 'Time to School', 'link'])
+                body += results
+
+                html += '<tr><td colspan=100%><hr></td></tr>'
+                html += '</table></body></html>'
+                # htmlformat = MIMEText(html, 'html')
+
+                # mymail = custom_email.simplemail(subj, body, sendto)
+                # mymail = custom_email.simplemail(subj, htmlformat, sendto)
+
+                # print(body)
+                # print(html)
             else:
                 body = 'No new listings found'
+                html = 'No new listings found.'
                 subj = '0 New Real Estate Listings for ' + str(datetime.date.today())
 
             try:
-                mymail = custom_email.simplemail(subj, body, sendto)
-                mymail.sendmail()
+                mymail = custom_email.simplemail(subj, body, sendto, html=html)
+                # mymail = custom_email.simplemail(subj, body, sendto)
+                mymail.sendhtml()
                 print("Email sent.")
                 logging.info('Emails sent to: ' + str(sendto))
             except Exception as e:

+ 8 - 4
landsearch.conf

@@ -1,6 +1,6 @@
 [Search]
 ## Accepts Gwinnett, Ballow, Hall, Jackson, and/or Walton.  Seperate multiple counties with comma.  Default is all 5 counties
-county = Barrow
+county = Hall
 
 ## Accepts farm, house, and/or land.  Seperate multiples with comman.  Default is all 3
 ## land typically refers to land-lots
@@ -16,13 +16,17 @@ type = farm
 ; upper_bedrooms = 10
 
 ## It true, sends email of results (whether or not new listings are found)
-email = true
+email = False
 
 ## Live_google will fetch actual time-to-school and time-to-work results from Google API.
 ## There may be a cost for this service, thus it can be turned off for testing.
-live_google = True
+live_google = False
 
 [Logging]
 log_file = landsearch.log
 ## log level accepts 10, 20, 30, 40, 50.  10 - Debug (most verbose) | 50 - Warning (least verbose)
-logging_level = 10
+logging_level = 10
+
+[Email]
+## Comma separated list of emails to send results to
+recipients = M_Stagl@hotmail.com, stagl.mike@gmail.com