Friday, November 6, 2015

Sending an email using CLI and Python on Onion Omega

I received my Onion Omega which I backed on Kickstarter in  April, today and being a weekend wanted to start off with something simple. I've programmed in python before and while browsing the FAQ and eventually the OpenWRT pages about installing python I saw the python-email library. So I decided to write a python script to send an email from the Onion Omega to my Gmail address. The idea being that once I connect some hardware like a switch or my home door bell to the Onion, it can email me if there is a new activity.
The first thing I searched for was how to send email using the CLI. I found this useful link (http://wiki.openwrt.org/doc/howto/smtp.client) and decided to use mailsend to try and send an email. Here are the steps that I followed:
Step 1: Install mailsend
opkg –install mailsend
Step 2: Use mailsend to send an email to my account. I had to experiment with different options but eventually the following worked
mailsend -to recipient@gmail.com -from youruserid@yourhost.com -ssl -port 465 -auth-login -smtp host236.hostmonster.com -sub test +cc +bc -v -useryouruserid@yourhost.com -pass “yourpassword” -M "Your message here"
Somehow I’m unable to send an email from my Gmail account so I used another host that my company uses.
Sending emails via Python Script
Step 1: Install Python (http://wiki.openwrt.org/doc/software/python)
Install python on Onion. I tried installing python-email only but the library had dependencies to many other libraries and after fixing those dependencies, I still had more dependencies. So I decided to install complete python instead of python-light
opkg -update
opkg –install python
Step 2: Write the script to send an email
#!/usr/bin/python
import smtplib
sender = ' youruserid@yourhost.com '
toaddrs = “recipient@gmail.com '
message = """From: Onion Omega Onion@onionomega.com
To: Recipient < recipient@gmail.com >
Subject: SMTP e-mail test
This is a test e-mail message.
"""
#Credentials
password = 'yourpasswordhere'
#The actual mail send
server = smtplib.SMTP_SSL('Your SMTP server address here :465') #(‘Host:Port’)
server.login(sender,password)
server.sendmail(sender, toaddrs, message)
server.quit()
print "done"
Success!
gmail.JPG
Links:
http://www.tutorialspoint.com/python/python_sending_email.htm
Another example to send email using SSL via python
http://stackoverflow.com/questions/24672079/send-email-using-smtp-ssl-port-465

UPDATE: The tutorial is now part of the official Onion Tutorials list! You can find it on https://wiki.onion.io/Tutorials/Sending-Emails-With-Python