Anvil Advent Calendar
Build a web app every day until Christmas, with nothing but Python!
Give Your Christmas Tree an Email Address
It’s the last week before Christmas, and you’re still busy at the office. If you’re like most office workers, much of your work consists of sending email. Why not control your Christmas lights by sending email too?
To do this, we’re going to update our Raspberry-Pi-controlled Christmas lights to receive email! We already have server functions to control the lights, so we just need to add the Email service, and write the following code in a Server Module:
@anvil.email.handle_message
def incoming_email(msg):
subject = msg.subject
if "on" in msg.subject.lower():
anvil.server.call('lights_on')
elif "off" in msg.subject.lower():
anvil.server.call('lights_off')
We’ll see at the bottom of our editor that this app can now respond to email:
We can send email to any address at that domain, and it will trigger our incoming_email
function! And we can pick a nicer domain by publishing our app:
That’s better!
Respond only to me
There’s one problem here – now anyone can send email to your Christmas tree! Not to worry - if your email provider supports DKIM (most of them do), we can verify that the email really comes from you!
Just modify your code to the following:
@anvil.email.handle_message(require_dkim=True)
def incoming_email(msg):
# Add this part:
if msg.envelope.from_address != 'meredydd@anvil.works':
raise anvil.email.DeliveryFailure("Not an authorised user")
subject = msg.subject
if "on" in msg.subject.lower():
anvil.server.call('lights_on')
elif "off" in msg.subject.lower():
anvil.server.call('lights_off')
Now, if you send email from the wrong address – or try to spoof it as coming from meredydd@anvil.works
– the app will reject delivery.
Now finish those emails, and grab a cup of something warm and spicy!
Give the Gift of Python
Share this post: