BBC iPlayer alerter – Part 3: Email

Before reading this article you should read the previous two posts of this series: BBC iPlayer alerter – Part 1: JSON processing, and BBC iPlayer alerter – Part 2: Data storage.

The final thing I had to prove was that I could send an email from a Python script. A very trivial task as it turned out:

#!/usr/bin/python

import smtplib

sender = 'sender@address.co.uk'
receivers = ['recipient@address.co.uk']

message = """From: From sender <sender@address.co.uk>
To: To recipient <recipient@address.co.uk>
Subject: SMTP e-mail test

Email text ...
"""

try:
smtpObj = smtplib.SMTP('mail.address.co.uk', 25)
smtpObj.login("smtpuser", "smtppwd" )
smtpObj.sendmail(sender, receivers, message)
print ("Successfully sent email")
except SMTPException:
print ("Error: unable to send email")

Bringing all 3 elements together was less trivial – in essence I create arrays of RadioShow objects and compare those. Hopefully the comments in the code will explain most of the rest (please note – the WordPress <code> tags have messed up the indentation of my Python, which, if you know Python, is a big deal – I’ll try and fix this at a later date):

#!/usr/bin/python

from urllib import request
import json
import pymysql
import datetime
import smtplib
import re

# get the current shows as json feed
url = "http://www.bbc.co.uk/radio4extra/programmes/genres/drama/current.json"
response = request.urlopen(url)

encoding = response.headers.get_content_charset()
json_object = json.loads(response.read().decode('utf-8'))

class RadioShow:
def __init__(self, id, title, short_synopsis, current):
self.id = id
self.title = title
self.short_synopsis = short_synopsis
self.current = current

#create an array to hold the current shows from the json
radio_shows = []
#create an array to hold the existing shows from the database
existing_radio_shows = []
#new shows - add these to the email alert, and also to the database
new_radio_shows = []
#old shows - update these in the database so that current = n
old_radio_shows = []

current_date = datetime.datetime.now().strftime("%Y-%m-%d")

programmes = json_object['category_slice']['programmes']

i = 0

# read the current shows into the programmes array
for program in programmes:
#print (program['title'])
#print (program['short_synopsis'])
radio_shows.append(RadioShow(i,program['title'],program['short_synopsis'], 'Y'))
i += i

if len(radio_shows) == 0:
print("ERROR: no shows found from the BBC website")
exit()

#for item in radio_shows:
#print(item.title)
#print(item.short_synopsis)

# connect to the mysql database

conn = pymysql.connect(host='127.0.0.1', unix_socket='/var/run/mysqld/mysqld.sock', user='username', passwd='pwd', database='radioshows')

cur = conn.cursor()

cur.execute("SELECT id,title,short_synopsis,current,detecteddt FROM radio_4_extra WHERE current='Y'")

for row in cur:
existing_radio_shows.append(RadioShow(row[0],row[1],row[2],row[3]))

#loop through the radio shows from the json to check for any new ones
for item in radio_shows:
#print("first for loop")
exists = False
for existingitem in existing_radio_shows:
#print(item.title + " " + existingitem.title)
if item.title == existingitem.title:
exists = True
break
if exists == False:
# insert into database, and into the list for emailing
#print("Execute insert")
cur.execute("INSERT INTO radio_4_extra (title,short_synopsis,current,detecteddt) VALUES ('%s','%s','Y','%s')" % (re.escape(item.title),re.escape(item.short_synopsis),current_date))
new_radio_shows.append(RadioShow(1,item.title,item.short_synopsis, 'Y'))
conn.commit()

#loop through the radio shows from the database to check if any have gone from the json
for existingitem in existing_radio_shows:
#print("second for loop")
exists = False
for item in radio_shows:
if existingitem.title == item.title:
exists = True
break
if exists == False:
# its not there anymore - update the existing item so current=N
#print("Execute update")
cur.execute("UPDATE radio_4_extra SET current='N' WHERE id=%d" % (existingitem.id))
old_radio_shows.append(RadioShow(1,item.title,item.short_synopsis, 'Y'))
conn.commit()

cur.close()
conn.close()

# send an email
sender = 'sender@address.co.uk'
receivers = ['recipient@address.co.uk']

message = """From: From sender <sender@address.co.uk>
To: To recipient<recipient@address.co.uk>
Subject: Radio Show Alert

New shows detected ...

"""

for item in new_radio_shows:
message += item.title
message += "\n"
message += item.short_synopsis
message += "\n\n"

try:
smtpObj = smtplib.SMTP('mail.address.co.uk', 25)
smtpObj.login("smtpuser", "smtppwd" )
smtpObj.sendmail(sender, receivers, message)
#print ("Successfully sent email")
except SMTPException:
exit()
#print ("Error: unable to send email")

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: