Skip to content

Instantly share code, notes, and snippets.

@greencoder
Created February 6, 2017 21:32
Show Gist options
  • Save greencoder/79c0608bf2c99eea732340c92a5a3af9 to your computer and use it in GitHub Desktop.
Save greencoder/79c0608bf2c99eea732340c92a5a3af9 to your computer and use it in GitHub Desktop.
Email myself the Weather 5280 10-Day Accumulated Snowfall Plot
import requests
import smtplib
import sys
import time
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email import Encoders
# Fetch the 240 hour image
now = int(time.time())
image_url = 'https://weather5280.s3-us-west-2.amazonaws.com/gfs/06z/denver/gfs-total-snow-accum-15/total_accum_15_240.png?%s' % now
image_response = requests.get(image_url)
# Save the image
if image_response.status_code == 200:
image_filename = 'total_accum_15_240.png'
with open(image_filename, 'wb') as f:
f.write(image_response.content)
else:
sys.exit('Could not fetch image.')
# Create the message
msg_host = 'SMTP SERVER TO USE'
msg_from = 'EMAIL TO SEND FROM ADDRESS'
msg_pass = 'EMAIL TO SEND FROM PASSWORD'
msg_to = 'EMAIL ADDRESS TO SEND TO'
# Create the root message and fill in the from, to, and subject headers
msg = MIMEMultipart('related')
msg.preamble = 'This is a multi-part message in MIME format.'
msg['Subject'] = 'Denver 10-Day Accumulated Snowfall (15:1)'
msg['From'] = msg_from
msg['To'] = msg_to
# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to display.
msg_alternative = MIMEMultipart('alternative')
msg.attach(msg_alternative)
msg_text = MIMEText('This is the alternative plain text message.')
msg_alternative.attach(msg_text)
# We reference the image in the IMG SRC attribute by the ID we give it below
msg_text = MIMEText('<img src="cid:image1">', 'html')
msg_alternative.attach(msg_text)
# This example assumes the image is in the current directory
filepath = open('total_accum_15_240.png', 'rb')
msg_image = MIMEImage(filepath.read())
filepath.close()
# Define the image's ID as referenced above
msg_image.add_header('Content-ID', '<image1>')
msg.attach(msg_image)
# Send the image
mailServer = smtplib.SMTP(msg_host, 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(msg_from, msg_pass)
print mailServer.sendmail(msg_from, msg_to, msg.as_string())
mailServer.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment