Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Rkauff/67377bfb1d8c92758b881e6b35b6e458 to your computer and use it in GitHub Desktop.
Save Rkauff/67377bfb1d8c92758b881e6b35b6e458 to your computer and use it in GitHub Desktop.
Use Python 3 to send an email with an attachment using Gmail
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 23 18:58:46 2017
@author: Ryan
"""
'''
This script does a couple things.
1) It goes out to the New York Federal Reserve website and scrapes the fed funds page.
2) Parses the date to get the current fed rate, and the corresponding date of that rate; the prior fed rate and the corresponding date of that rate.
3) Then it passes that data to a data frame and saves that data down in an Excel file (.xlsx) for later use, and/or analysis.
4) Finally, it emails the newly created Excel file via Gmail to anyone the user wants.
I just built this because I thought it would be fun. Use at your own risk.
import smtplib
import os
import sys
import requests
import bs4
import datetime
from pandas import DataFrame
from pandas import ExcelWriter
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
now = datetime.datetime.now()
now1 = now.strftime("%Y-%m-%d %I:%M %p")
now2 = now.strftime("%Y-%m-%d")
out_path = "THE PATH YOU WANT TO SAVE THE RESULTING EXCEL FILE GOES HERE"
#Step 1: download a webpage with requests.get
fed_url = requests.get('https://apps.newyorkfed.org/markets/autorates/fed%20funds')
#Step 2: Pass only the text element of the page to a variable
fed = bs4.BeautifulSoup(fed_url.text, 'lxml')
#Step 3: Parse the page for the most recent rate, date, and the second most recent rate and date
rate = fed.select('td.dirColTight.numData')
date = fed.select('td.dirColLTight')
todays_rate = float(rate[0].getText())
todays_date = str(date[0].getText())
yest_rate = float(rate[6].getText())
yest_date = str(date[1].getText())
#Step 4: Determine if the rate changed
diff = todays_rate - yest_rate
def send_to_excel():
#First create the data frame:
df = DataFrame({'Current Rate as of:':[todays_date], 'Rate':[todays_rate]})
df1 = DataFrame({'Previous Rate as of:':[yest_date], 'Rate':[yest_rate]})
df2 = DataFrame({'Rate Difference:':[int(todays_rate)-int(yest_rate)]})
#Next, write the data frames to an excel file
writer = ExcelWriter(out_path + 'Fed Funds Rate as of ' + now2 + '.xlsx')
df.to_excel(writer,sheet_name ='Fed Data',startrow=0, startcol=0)
df1.to_excel(writer,sheet_name ='Fed Data',startrow=0, startcol=3)
df2.to_excel(writer,sheet_name ='Fed Data',startrow=0, startcol=6)
writer.save()
COMMASPACE = ', '
def send_email():
sender = 'SENDER EMAIL GOES HERE'
gmail_password = 'YOUR PASSWORD GOES HERE'
recipients = ['RECIPIENT EMAIL ADDRESS(ES) HERE']
# Create the enclosing (outer) message
outer = MIMEMultipart()
outer['Subject'] = 'Fed Funds Rate as of ' + now2
outer['To'] = COMMASPACE.join(recipients)
outer['From'] = sender
outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'
# List of attachments
attachments = [out_path + 'Fed Funds Rate as of ' + now2 + '.xlsx']
# Add the attachments to the message
for file in attachments:
with open(file, 'rb') as fp:
msg = MIMEBase('application', "octet-stream")
msg.set_payload(fp.read())
encoders.encode_base64(msg)
msg.add_header('Content-Disposition', 'Fed Funds File', filename=os.path.basename(file))
outer.attach(msg)
composed = outer.as_string()
# Send the email
try:
with smtplib.SMTP('smtp.gmail.com', 587) as s:
s.ehlo()
s.starttls()
s.ehlo()
s.login(sender, gmail_password)
s.sendmail(sender, recipients, composed)
s.close()
except:
print("Unable to send the email. Error: ", sys.exc_info()[0])
raise
def main():
send_to_excel()
send_email()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment