Raspberry Pi Pico Tips and Tricks

Tuesday 11 April 2023

Sending an email from a Raspberry Pi Pico W

 Sending emails programmatically is a useful function for those sort of events where you have your Pico measuring something and when it needs some higher attention it sends a call for help. Kind of the Pico version of shining the bat symbol in the sky. I’m sure that there are better analogies, but that’s what I think of when I imagine a Raspberry Pi Pico sending an email.

Whatever the occasion, the Pico is up for the job.

I've written this short explanation as part of the much larger book 'Raspberry Pi Pico Tips and Tricks'. You can download it for free from here.

The slightly tricky part of email.

Well… Not so much tricky, but being prepared. An email needs to originate from an email service (like Google or Outlook or ProtonMail). Our Pico isn’t quite capable enough to run an email server for us, but it can contact one that we have an account with and instruct it to send one on our behalf. That means that we need to do a little bit of research prior to setting up our code so that we have the details that are required to negotiate with our email server.

In this example we’ll use the Gmail service to send our email for us. This means that we are going to need to know details similar to the following;

  • Server: smtp.gmail.com (this is hard coded into the script below)
  • Sender Email: The email address that we will be sending from. I.e. Our Gmail address of (the sender).
  • Sender Password: the password of the sender account. For Raspberry Pi Pico to send an email with Gmail first, we need to create an ‘App password’ using our Gmail account. An app password is a unique password generated for an app or device, as the device in this case (our Pico) will not be able to prompt for a verification code. In these cases, we can generate an app password to use instead of our regular password for accessing Gmail. We then use this password on the device. The device password is only valid for a specific device and is designed to protect the main account if the Pico gets out of control and needs to be shut down because it starts to spam people. Do a Google search for ‘create Gmail app password’ and it will guide you to the right place.
  • Server port: 465 (this the port for SSL and will allow for a secure connection to the mail server)

If you’re not using Gmail you will need to determine the appropriate smtp server name for your service and the port that they use. This will vary from provider to provider and might require some googling.

We’ll also need some basics like our SSID name and username / password for connecting to the WiFi connection that will be used. Just like we needed when setting up WiFi earlier.

All this good information above can be captured in our ‘secrets.py’ file that we can keep on the Pico so that we don’t need to expose those more sensitive details in our main code. We first saw this file used in the section where we were serving a web page using the Pico. For this example it will look a little like the following (but with your secrets in the appropriate places);

secrets = {
    'ssid': '<your ssid>',
    'pw': '<your password>',
    'ip': '<the static IP address for the Pico',
    'netmask': '<the netmask for your network, but probably something like 255.25\
5.255.0>',
    'gateway': '<Your gateway address>',
    'dns': '<The DNS server you are going to use>',
    'sender_email': '<the email address of the Gmail account you will use>',
    'sender_name': '<Your sender name>',
    'sender_password': '<the App / device password that you set up in Gmail>', 
    'recipient_email': '<the email address of the recipient>' 
    }

The Code

The email function is driven by the umail module. This has been published on GitHub by shawwwn. To make use of the module we will need to download it from GitHub and then copy it over to our Pico. I found this most easily accomplished by first downloading the file to the main computer and then going File >> Open on Thonny and selecting the appropriate file. From there go File >> Save as… and select the Pico as the location to save the file (making sure to save it with the appropriate name (umail.py)).

Our code is fairly straight forward in that it imports the appropriate modules, creates the WiFi connection and then sends the email (not forgetting the secrets file) and looks like the following;

import network
import time
import umail
from secrets import secrets

# Set up Wifi
ssid = secrets['ssid']
password = secrets['pw']
rp2.country('NZ') # change to your country code

wlan = network.WLAN(network.STA_IF)

ip = secrets['ip']
netmask = secrets['netmask']
gateway = secrets['gateway']
dns = secrets['dns']

wlan.active(True) # activate the interface
if not wlan.isconnected(): # check if connected to an AP
    print('Connecting to network...')
    wlan.connect(ssid, password) # connect to an AP
    wlan.ifconfig((ip,netmask,gateway,dns))
    while not wlan.isconnected(): # wait till we are connected
        print('.', end='')
        time.sleep(0.1)
    print()
    print('Connected:', wlan.isconnected())
else:
    print("Already connected!")

# Email details
sender_email = secrets['sender_email']
sender_name = secrets['sender_name']
sender_password = secrets['sender_password']
recipient_email = secrets['recipient_email'] 
email_subject ='Test Email from Raspberry Pi Pico'

# Connect to Gmail via SSL
smtp = umail.SMTP('smtp.gmail.com', 465, ssl=True)
# Login to the email account using the senders password
smtp.login(sender_email, sender_password)
# Specify the recipient
smtp.to(recipient_email)
# Write the email header
smtp.write("From:" + sender_name + "<"+ sender_email+">\n")
smtp.write("Subject:" + email_subject + "\n")
# Write the body of the email
smtp.write("Roses are red.\n")
smtp.write("Violets are blue.\n")
smtp.write("...\n")
# Send the email
smtp.send()
# Quit the email session

Obviously the content of the body of the email can be adjusted to accept information gleaned from sensors or similar important information. Separate each line out with a newline character and we’re good to go!

Don't forget, if you're looking for the book 'Raspberry Pi Pico Tips and Tricks'. You can download it for free (or donate if you wish) from here.

No comments:

Post a Comment