Skip to content

Instantly share code, notes, and snippets.

@mick-io
Created August 14, 2017 01:49
Show Gist options
  • Save mick-io/a20530bd8c2b8062a151a613ca30cea5 to your computer and use it in GitHub Desktop.
Save mick-io/a20530bd8c2b8062a151a613ca30cea5 to your computer and use it in GitHub Desktop.
Python SLC Weather Mailer
"""
Collects email address and names from a text field 'emails.txt' located in the
same directory. Send a weather daily weather forecast of Salt Lake City pulled
in the from the Open Weather Map Api via a gmail account.
"""
import getpass
import smtplib
import requests
def get_emails():
"""Returns a dictionary of email address and names from 'emails.txt' """
emails = {}
try:
email_file = open('emails.txt', 'r')
for line in email_file:
(email, name) = line.split(',')
emails[email] = name.strip()
except FileNotFoundError as err:
print(err)
return emails
def get_weather_forcast():
"""Request data from the API and constructs email body"""
api_key = input("Enter your Open Weather Map API Key")
url = "https://api.openweathermap.org/data/2.5"
url += "/weather?id=5780993&units=imperial&appid="
url += api_key
weather_request = requests.get(url)
weather_json = weather_request.json()
city = weather_json['name']
description = weather_json['weather'][0]['description']
temp_min = weather_json['main']['temp_min']
temp_max = weather_json['main']['temp_max']
forecast = 'The ' + city + ' forecast for today is '
forecast += description + ' with a high of ' + str(int(temp_max))
forecast += ' and a low of ' + str(int(temp_min)) + '.'
return forecast
def send_emails(emails, forecast):
"""
request gmail address to send from and password for that account from user.
Constructors the header of the email and sends the entire message.
"""
server = smtplib.SMTP('smtp.gmail.com', '587')
server.starttls()
from_email = input('gmail account to send from: ')
password = getpass.getpass('Password: ')
server.login(from_email, password)
# Sending email to address in 'emails.txt'
for to_email, name in emails.items():
message = "Today's Salt Lake City Forcast\n\n"
message += "Hello, " + name + "\n\n"
message += forecast
server.sendmail(from_email, to_email, message)
server.quit()
def main():
"""
arguments for send_emails are assigned based on return values of
emails and forecast
"""
emails = get_emails()
forecast = get_weather_forcast()
send_emails(emails, forecast)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment