aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMark Powers <mark@marks.kitchen>2020-09-20 01:07:23 +0000
committerMark Powers <mark@marks.kitchen>2020-09-20 01:07:23 +0000
commitb4441232cb2c54e7ab0173a09640eff3828017cd (patch)
tree459d422f093c5de07173469689ecc705a1ef7286
Initial commit
-rw-r--r--.gitignore3
-rw-r--r--README.md15
-rw-r--r--config.py37
-rwxr-xr-xdaily-update.py52
-rw-r--r--email_helper.py28
-rw-r--r--kitchen-update-email.py70
-rw-r--r--reminder.py21
7 files changed, 226 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..e84687f
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,3 @@
+__pycache__/
+config.ini
+
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..f826676
--- /dev/null
+++ b/README.md
@@ -0,0 +1,15 @@
+# Email Scripts
+Some misc scripts I use regarding email
+
+## email\_helper.py
+General purpose email reading/sending
+
+## kitchen-update-email.py
+Check if there is a new post on my website and email those signed up for email notifications
+
+## reminder.py
+Send an email based on args with the subject staring "REMINDER: ". This makes it easy to set up monthly/weekly/etc. reminders via crontab
+
+## daily-update.py
+Sends an update with news and weather about the day
+
diff --git a/config.py b/config.py
new file mode 100644
index 0000000..645288f
--- /dev/null
+++ b/config.py
@@ -0,0 +1,37 @@
+import os
+from configparser import ConfigParser
+
+config_path = "/home/mark/email-scripts/config.ini"
+
+config = ConfigParser()
+if os.path.isfile(config_path):
+ config.read(config_path)
+else:
+ if input("Config file not found, create one? (y/n)") == "y":
+ config_dict = {"email": {}, "database": {}, "weather": {}, "news": {}}
+ config_dict["email"]["server"] = input("Email server: ").strip()
+ config_dict["email"]["port"] = input("Email port: ").strip()
+ config_dict["email"]["name"] = input("Email name: ").strip()
+ config_dict["email"]["user"] = input("Email username name: ").strip()
+ config_dict["email"]["pass"] = input("Email password: ").strip()
+
+ if input("Configure database? (y/n)") == "y":
+ config_dict["database"]["db"] = input("DB name: ").strip()
+ config_dict["database"]["user"] = input("DB user: ").strip()
+ config_dict["database"]["pass"] = input("DB password: ").strip()
+
+ if input("Configure weather? (y/n)") == "y":
+ config_dict["weather"]["lat"] = input("Latitude: ").strip()
+ config_dict["weather"]["long"] = input("Longitude: ").strip()
+
+ if input("Configure century old news? (y/n)") == "y":
+ print("Go to https://chroniclingamerica.loc.gov/ and find a newspaper to follow")
+ print("Open the issue for that newspaper, and replace the date in the URL with %%s")
+ config_dict["news"]["urls"] = input("Enter URLs formatted as described above, comma seperated: ").strip()
+ config_dict["news"]["names"] = input("Enter names for each respective URL, comma seperated: ").strip()
+
+ input("Press enter to save config")
+ config.read_dict(config_dict)
+ with open(config_path, 'w') as configfile:
+ config.write(configfile)
+
diff --git a/daily-update.py b/daily-update.py
new file mode 100755
index 0000000..7109b99
--- /dev/null
+++ b/daily-update.py
@@ -0,0 +1,52 @@
+#!/usr/bin/python3
+
+import smtplib
+import sys
+import time
+import requests
+
+from datetime import date
+from bs4 import BeautifulSoup
+from email.mime.text import MIMEText
+from email.utils import formatdate
+
+import email_helper
+from config import config
+
+def get_weather():
+ print("getting weather")
+ weather_url = "https://forecast.weather.gov/MapClick.php?lon=%s&lat=%s" % (config["weather"]["lon"], config["weather"]["lat"])
+ soup = BeautifulSoup(requests.get(weather_url).text, features="lxml")
+ return str(soup.select("#detailed-forecast")[0])
+
+def get_old_news():
+ print("getting old news")
+ year = int(date.today().strftime("%Y")) - 100
+ century_ago = str(year) + date.today().strftime("-%m-%d")
+ news_text = ""
+ urls = config["news"]["urls"].split(",")
+ names = config["news"]["names"].split(",")
+ for i in range(len(urls)):
+ full_url = urls[i] % century_ago
+ name = names[i]
+ if requests.get(full_url).status_code != 404:
+ news_text += '<a href="%s">%s %s</a>\n' % (full, name, century_ago)
+ return news_text
+
+def format_email():
+ print("forming email")
+ return '%s%s' % (get_old_news(), get_weather())
+
+def send_update_email():
+ frm = config["email"]["user"]
+ name = config["email"]["name"]
+
+ today = date.today().strftime("%b %d")
+ subject = "Updates for " + today
+
+ body = format_email()
+ email_helper.send(frm, name, frm, subject, body, "html")
+
+if __name__ == "__main__":
+ send_update_email()
+
diff --git a/email_helper.py b/email_helper.py
new file mode 100644
index 0000000..d3edfb8
--- /dev/null
+++ b/email_helper.py
@@ -0,0 +1,28 @@
+import smtplib
+from email.mime.text import MIMEText
+from email.utils import formatdate
+
+from config import config
+
+def send(frm, name, to, subject, body, subtype="plain"):
+ """Send a email to the given address, from the given address and name with the subject and body
+ """
+ try:
+ server = smtplib.SMTP(config["email"]["server"], int(config["email"]["port"]))
+ server.ehlo()
+ server.starttls()
+ server.login(config["email"]["user"], config["email"]["pass"])
+
+ frm = "%s <%s>" % (name, frm)
+ e = MIMEText(body, subtype)
+ e['Subject'] = subject
+ e['From'] = frm
+ e['To'] = to
+ e.add_header('Date', formatdate())
+
+ server.sendmail(frm, to, e.as_string())
+
+ except Exception as e:
+ print("error")
+ print(e)
+
diff --git a/kitchen-update-email.py b/kitchen-update-email.py
new file mode 100644
index 0000000..821127e
--- /dev/null
+++ b/kitchen-update-email.py
@@ -0,0 +1,70 @@
+import smtplib
+from email.mime.text import MIMEText
+from email.utils import formatdate
+import pymysql
+import sys
+
+import email_helper
+from config import config
+
+def get_last_sent_update(cursor):
+ cursor.execute("SELECT last_update FROM updates;")
+ return cursor.fetchone()[0]
+
+def get_later_post(cursor, last):
+ cursor.execute("SELECT id,type FROM posts where id > " + str(last) +" ORDER BY id asc")
+ return cursor.fetchone()
+
+def set_last_sent_update(cursor, db, post_id):
+ cursor.execute("UPDATE updates SET last_update=" + str(post_id)+ " where id=1")
+ db.commit()
+
+def get_emails(cursor):
+ cursor.execute("SELECT name, address FROM emails")
+ return cursor.fetchall()
+
+def add_update(cursor, db, post_id):
+ cursor.execute("insert into updates values (1, " +str(post_id)+", NOW())")
+ db.commit()
+
+def handle_update():
+ """ Check for a new post on my website and email everyone on the list
+ if there is one.
+ """
+
+ db = pymysql.connect("localhost", config["database"]["user"], config["database"]["pass"], config["database"]["db"])
+ cursor = db.cursor()
+
+ last = get_last_sent_update(cursor)
+
+ new_post = get_later_post(cursor, last)
+ if not new_post:
+ print("no new post")
+ sys.exit()
+ if new_post[1] == 'index':
+ print("ignoring index post")
+ sys.exit()
+ print(new_post)
+
+ set_last_sent_update(cursor, db, new_post[0])
+ emails = get_emails(cursor)
+
+ name = config["email"]["name"]
+ frm = config["email"]["user"]
+ subject = "marks.kitchen update"
+ for email in emails:
+ to = email[1]
+ body = """
+ Hi """ + email[0] + """!
+
+ There is a new post on marks.kitchen! Check it out: https://marks.kitchen/post/"""+new_post[1]+"""/"""+str(new_post[0])+"""
+
+ Mark (mark@marks.kitchen)
+ """
+ email_helper.send(frm, name, to, subject, body)
+ add_update(cursor, db, new_post[0])
+ db.close()
+
+if __name__ == "__main__":
+ handle_update()
+
diff --git a/reminder.py b/reminder.py
new file mode 100644
index 0000000..5fd0025
--- /dev/null
+++ b/reminder.py
@@ -0,0 +1,21 @@
+import smtplib
+from email.mime.text import MIMEText
+from email.utils import formatdate
+import sys
+
+import email_helper
+from config import config
+
+def send_reminder():
+ """Sends a reminder email based on the arguments for easy scripting
+ Usage: python3 reminder.py <subject> <body...>
+ """
+
+ name = config["email"]["name"]
+ user = config["email"]["user"]
+ subject = "REMINDER: %s" % sys.argv[1]
+ body = sys.argv[2] if len(sys.argv) > 2 else ""
+ email_helper.send(user, name, user, subject, body)
+
+if __name__ == "__main__":
+ send_reminder()