MicroPython: Send Sensor Readings via email with the ESP32/ESP826 (BME280)

In this tutorial, you’ll learn how to program the ESP32 and ESP8266 boards with MicroPython to send sensor readings to your email. As an example, we’ll send temperature, humidity, and pressure from a BME280 sensor, but you can easily modify the project to use a different sensor.

MicroPython Send Sensor Readings via email with the ESP32 ESP826 NodeMCU BME280

Are you going to use a different sensor? We have guides for the following sensors that will help you get started:

Prerequisites

New to MicroPython? You can get started here: Getting Started with MicroPython on ESP32 and ESP8266.

To follow this tutorial you need MicroPython firmware installed in your ESP32 or ESP8266 boards. You also need an IDE to write and upload the code to your board. We suggest using Thonny IDE or uPyCraft IDE:

Or, if you’re familiar with VS Code, you may want to use the PyMakr extension:

For a comparison between different MicroPython IDEs, read: MicroPython IDEs for ESP32 and ESP8266.

Learn more about MicroPython: MicroPython Programming with ESP32 and ESP8266 eBook.

Parts Required

For this tutorial you need the following parts:

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

uMail Module

To easily send emails with MicroPython, we’ll use a module called uMail. This module is not part of the standard collection of MicroPython libraries, so we’ll need to upload it separately to our board—we’ll provide instructions for this later in the tutorial.

To get familiar with sending emails using this library, take a look at our tutorial:

BME280 Module

To read from the BME280 sensor, we’ll use a module that’s not also part of the standard MicroPython libraries by default. So, we’ll need to upload it to the board before start writing the code. The BME280 module can be found here.

For a getting started guide to learn how to interface the BME280 with the ESP32/ESP8266 using MicroPython, you can read the following tutorial:

Sender Email (New Account)

We recommend creating a new email account to send the emails to your main personal email address. Do not use your main personal email to send emails via ESP32 or ESP8266. If something goes wrong in your code or if by mistake you make too many requests, you can be banned or have your account temporarily disabled. We recommend using a Gmail account, but other email providers should also work.

Create an App Password

You need to create an app password so that new devices can send emails using your Gmail account. An App Password is a 16-digit passcode that gives a less secure app or device permission to access your Google Account. Learn more about sign-in with app passwords here.

You can follow these instructions to learn how to create your app password.

If you’re using another email provider, check how to create an app password. You should be able to find the instructions with a quick google search “your_email_provider + create app password”.

Wiring the BME280

In this tutorial, we’ll create a sample project that sends BME280 sensor readings to your email. So, you need to wire the BME280 sensor to your board. Follow one of the next schematic diagrams.

ESP32 with BME280

We’re going to use I2C communication with the BME280 sensor module. Wire the sensor to the default ESP32 SCL (GPIO 22) and SDA (GPIO 21) pins, as shown in the following schematic diagram.

ESP32 BME280 Sensor Temperature Humidity Pressure Wiring Diagram Circuit

ESP8266 with BME280

We’re going to use I2C communication with the BME280 sensor module. For that, wire the sensor to the ESP8266 SDA (GPIO 4) and SCL (GPIO 5) pins, as shown in the following schematic diagram.

ESP8266 NodeMCU BME280 Sensor Temperature Humidity Pressure Wiring Diagram Circuit

Not familiar with the BME280 with the ESP32/ESP8266 using MicroPython? Read this tutorial: MicroPython: BME280 with ESP32 and ESP8266 (Pressure, Temperature, Humidity).

Uploading the uMail Module

To send the emails, we’ll use the uMail module. You can check its Github page and several examples here. This library isn’t part of the standard MicroPython library by default. So, you need to upload the following file to your ESP32/ESP8266 board (save it with the name umail.py) before using the library.

# Complete project details: https://RandomNerdTutorials.com/micropython-send-emails-esp32-esp826/
# uMail (MicroMail) for MicroPython
# Copyright (c) 2018 Shawwwn <[email protected]> https://github.com/shawwwn/uMail/blob/master/umail.py
# License: MIT
import usocket

DEFAULT_TIMEOUT = 10 # sec
LOCAL_DOMAIN = '127.0.0.1'
CMD_EHLO = 'EHLO'
CMD_STARTTLS = 'STARTTLS'
CMD_AUTH = 'AUTH'
CMD_MAIL = 'MAIL'
AUTH_PLAIN = 'PLAIN'
AUTH_LOGIN = 'LOGIN'

class SMTP:
    def cmd(self, cmd_str):
        sock = self._sock;
        sock.write('%s\r\n' % cmd_str)
        resp = []
        next = True
        while next:
            code = sock.read(3)
            next = sock.read(1) == b'-'
            resp.append(sock.readline().strip().decode())
        return int(code), resp

    def __init__(self, host, port, ssl=False, username=None, password=None):
        import ssl
        self.username = username
        addr = usocket.getaddrinfo(host, port)[0][-1]
        sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
        sock.settimeout(DEFAULT_TIMEOUT)
        sock.connect(addr)
        if ssl:
            sock = ssl.wrap_socket(sock)
        code = int(sock.read(3))
        sock.readline()
        assert code==220, 'cant connect to server %d, %s' % (code, resp)
        self._sock = sock

        code, resp = self.cmd(CMD_EHLO + ' ' + LOCAL_DOMAIN)
        assert code==250, '%d' % code
        if not ssl and CMD_STARTTLS in resp:
            code, resp = self.cmd(CMD_STARTTLS)
            assert code==220, 'start tls failed %d, %s' % (code, resp)
            self._sock = ssl.wrap_socket(sock)

        if username and password:
            self.login(username, password)

    def login(self, username, password):
        self.username = username
        code, resp = self.cmd(CMD_EHLO + ' ' + LOCAL_DOMAIN)
        assert code==250, '%d, %s' % (code, resp)

        auths = None
        for feature in resp:
            if feature[:4].upper() == CMD_AUTH:
                auths = feature[4:].strip('=').upper().split()
        assert auths!=None, "no auth method"

        from ubinascii import b2a_base64 as b64
        if AUTH_PLAIN in auths:
            cren = b64("\0%s\0%s" % (username, password))[:-1].decode()
            code, resp = self.cmd('%s %s %s' % (CMD_AUTH, AUTH_PLAIN, cren))
        elif AUTH_LOGIN in auths:
            code, resp = self.cmd("%s %s %s" % (CMD_AUTH, AUTH_LOGIN, b64(username)[:-1].decode()))
            assert code==334, 'wrong username %d, %s' % (code, resp)
            code, resp = self.cmd(b64(password)[:-1].decode())
        else:
            raise Exception("auth(%s) not supported " % ', '.join(auths))

        assert code==235 or code==503, 'auth error %d, %s' % (code, resp)
        return code, resp

    def to(self, addrs, mail_from=None):
        mail_from = self.username if mail_from==None else mail_from
        code, resp = self.cmd(CMD_EHLO + ' ' + LOCAL_DOMAIN)
        assert code==250, '%d' % code
        code, resp = self.cmd('MAIL FROM: <%s>' % mail_from)
        assert code==250, 'sender refused %d, %s' % (code, resp)

        if isinstance(addrs, str):
            addrs = [addrs]
        count = 0
        for addr in addrs:
            code, resp = self.cmd('RCPT TO: <%s>' % addr)
            if code!=250 and code!=251:
                print('%s refused, %s' % (addr, resp))
                count += 1
        assert count!=len(addrs), 'recipient refused, %d, %s' % (code, resp)

        code, resp = self.cmd('DATA')
        assert code==354, 'data refused, %d, %s' % (code, resp)
        return code, resp

    def write(self, content):
        self._sock.write(content)

    def send(self, content=''):
        if content:
            self.write(content)
        self._sock.write('\r\n.\r\n') # the five letter sequence marked for ending
        line = self._sock.readline()
        return (int(line[:3]), line[4:].strip().decode())

    def quit(self):
        self.cmd("QUIT")
        self._sock.close()

View raw code

Regardless of the IDE you’re using, these are the general instructions to upload the uMail library to your board:

  1. First, make sure your board is running MicroPython firmware—check the Prerequisites section.
  2. Create a new file in your IDE with the name umail.py and paste the previous code there. Save that file.
  3. Establish a serial communication with your board using your IDE.
  4. Upload the umail.py file to your board.
  5. At this point, the library should have been successfully uploaded to your board. Now, you can use the library functionalities in your code by importing the library: import umail.

Uploading the BME280 Module

To get temperature, humidity, and pressure from the BME280 sensor, we’ll use the following module (name it BME280.py before uploading it to your board).

from machine import I2C
import time

# BME280 default address.
BME280_I2CADDR = 0x76

# Operating Modes
BME280_OSAMPLE_1 = 1
BME280_OSAMPLE_2 = 2
BME280_OSAMPLE_4 = 3
BME280_OSAMPLE_8 = 4
BME280_OSAMPLE_16 = 5

# BME280 Registers

BME280_REGISTER_DIG_T1 = 0x88  # Trimming parameter registers
BME280_REGISTER_DIG_T2 = 0x8A
BME280_REGISTER_DIG_T3 = 0x8C

BME280_REGISTER_DIG_P1 = 0x8E
BME280_REGISTER_DIG_P2 = 0x90
BME280_REGISTER_DIG_P3 = 0x92
BME280_REGISTER_DIG_P4 = 0x94
BME280_REGISTER_DIG_P5 = 0x96
BME280_REGISTER_DIG_P6 = 0x98
BME280_REGISTER_DIG_P7 = 0x9A
BME280_REGISTER_DIG_P8 = 0x9C
BME280_REGISTER_DIG_P9 = 0x9E

BME280_REGISTER_DIG_H1 = 0xA1
BME280_REGISTER_DIG_H2 = 0xE1
BME280_REGISTER_DIG_H3 = 0xE3
BME280_REGISTER_DIG_H4 = 0xE4
BME280_REGISTER_DIG_H5 = 0xE5
BME280_REGISTER_DIG_H6 = 0xE6
BME280_REGISTER_DIG_H7 = 0xE7

BME280_REGISTER_CHIPID = 0xD0
BME280_REGISTER_VERSION = 0xD1
BME280_REGISTER_SOFTRESET = 0xE0

BME280_REGISTER_CONTROL_HUM = 0xF2
BME280_REGISTER_CONTROL = 0xF4
BME280_REGISTER_CONFIG = 0xF5
BME280_REGISTER_PRESSURE_DATA = 0xF7
BME280_REGISTER_TEMP_DATA = 0xFA
BME280_REGISTER_HUMIDITY_DATA = 0xFD


class Device:
  """Class for communicating with an I2C device.

  Allows reading and writing 8-bit, 16-bit, and byte array values to
  registers on the device."""

  def __init__(self, address, i2c):
    """Create an instance of the I2C device at the specified address using
    the specified I2C interface object."""
    self._address = address
    self._i2c = i2c

  def writeRaw8(self, value):
    """Write an 8-bit value on the bus (without register)."""
    value = value & 0xFF
    self._i2c.writeto(self._address, value)

  def write8(self, register, value):
    """Write an 8-bit value to the specified register."""
    b=bytearray(1)
    b[0]=value & 0xFF
    self._i2c.writeto_mem(self._address, register, b)

  def write16(self, register, value):
    """Write a 16-bit value to the specified register."""
    value = value & 0xFFFF
    b=bytearray(2)
    b[0]= value & 0xFF
    b[1]= (value>>8) & 0xFF
    self.i2c.writeto_mem(self._address, register, value)

  def readRaw8(self):
    """Read an 8-bit value on the bus (without register)."""
    return int.from_bytes(self._i2c.readfrom(self._address, 1),'little') & 0xFF

  def readU8(self, register):
    """Read an unsigned byte from the specified register."""
    return int.from_bytes(
        self._i2c.readfrom_mem(self._address, register, 1),'little') & 0xFF

  def readS8(self, register):
    """Read a signed byte from the specified register."""
    result = self.readU8(register)
    if result > 127:
      result -= 256
    return result

  def readU16(self, register, little_endian=True):
    """Read an unsigned 16-bit value from the specified register, with the
    specified endianness (default little endian, or least significant byte
    first)."""
    result = int.from_bytes(
        self._i2c.readfrom_mem(self._address, register, 2),'little') & 0xFFFF
    if not little_endian:
      result = ((result << 8) & 0xFF00) + (result >> 8)
    return result

  def readS16(self, register, little_endian=True):
    """Read a signed 16-bit value from the specified register, with the
    specified endianness (default little endian, or least significant byte
    first)."""
    result = self.readU16(register, little_endian)
    if result > 32767:
      result -= 65536
    return result

  def readU16LE(self, register):
    """Read an unsigned 16-bit value from the specified register, in little
    endian byte order."""
    return self.readU16(register, little_endian=True)

  def readU16BE(self, register):
    """Read an unsigned 16-bit value from the specified register, in big
    endian byte order."""
    return self.readU16(register, little_endian=False)

  def readS16LE(self, register):
    """Read a signed 16-bit value from the specified register, in little
    endian byte order."""
    return self.readS16(register, little_endian=True)

  def readS16BE(self, register):
    """Read a signed 16-bit value from the specified register, in big
    endian byte order."""
    return self.readS16(register, little_endian=False)


class BME280:
  def __init__(self, mode=BME280_OSAMPLE_1, address=BME280_I2CADDR, i2c=None,
               **kwargs):
    # Check that mode is valid.
    if mode not in [BME280_OSAMPLE_1, BME280_OSAMPLE_2, BME280_OSAMPLE_4,
                    BME280_OSAMPLE_8, BME280_OSAMPLE_16]:
        raise ValueError(
            'Unexpected mode value {0}. Set mode to one of '
            'BME280_ULTRALOWPOWER, BME280_STANDARD, BME280_HIGHRES, or '
            'BME280_ULTRAHIGHRES'.format(mode))
    self._mode = mode
    # Create I2C device.
    if i2c is None:
      raise ValueError('An I2C object is required.')
    self._device = Device(address, i2c)
    # Load calibration values.
    self._load_calibration()
    self._device.write8(BME280_REGISTER_CONTROL, 0x3F)
    self.t_fine = 0

  def _load_calibration(self):

    self.dig_T1 = self._device.readU16LE(BME280_REGISTER_DIG_T1)
    self.dig_T2 = self._device.readS16LE(BME280_REGISTER_DIG_T2)
    self.dig_T3 = self._device.readS16LE(BME280_REGISTER_DIG_T3)

    self.dig_P1 = self._device.readU16LE(BME280_REGISTER_DIG_P1)
    self.dig_P2 = self._device.readS16LE(BME280_REGISTER_DIG_P2)
    self.dig_P3 = self._device.readS16LE(BME280_REGISTER_DIG_P3)
    self.dig_P4 = self._device.readS16LE(BME280_REGISTER_DIG_P4)
    self.dig_P5 = self._device.readS16LE(BME280_REGISTER_DIG_P5)
    self.dig_P6 = self._device.readS16LE(BME280_REGISTER_DIG_P6)
    self.dig_P7 = self._device.readS16LE(BME280_REGISTER_DIG_P7)
    self.dig_P8 = self._device.readS16LE(BME280_REGISTER_DIG_P8)
    self.dig_P9 = self._device.readS16LE(BME280_REGISTER_DIG_P9)

    self.dig_H1 = self._device.readU8(BME280_REGISTER_DIG_H1)
    self.dig_H2 = self._device.readS16LE(BME280_REGISTER_DIG_H2)
    self.dig_H3 = self._device.readU8(BME280_REGISTER_DIG_H3)
    self.dig_H6 = self._device.readS8(BME280_REGISTER_DIG_H7)

    h4 = self._device.readS8(BME280_REGISTER_DIG_H4)
    h4 = (h4 << 24) >> 20
    self.dig_H4 = h4 | (self._device.readU8(BME280_REGISTER_DIG_H5) & 0x0F)

    h5 = self._device.readS8(BME280_REGISTER_DIG_H6)
    h5 = (h5 << 24) >> 20
    self.dig_H5 = h5 | (
        self._device.readU8(BME280_REGISTER_DIG_H5) >> 4 & 0x0F)

  def read_raw_temp(self):
    """Reads the raw (uncompensated) temperature from the sensor."""
    meas = self._mode
    self._device.write8(BME280_REGISTER_CONTROL_HUM, meas)
    meas = self._mode << 5 | self._mode << 2 | 1
    self._device.write8(BME280_REGISTER_CONTROL, meas)
    sleep_time = 1250 + 2300 * (1 << self._mode)

    sleep_time = sleep_time + 2300 * (1 << self._mode) + 575
    sleep_time = sleep_time + 2300 * (1 << self._mode) + 575
    time.sleep_us(sleep_time)  # Wait the required time
    msb = self._device.readU8(BME280_REGISTER_TEMP_DATA)
    lsb = self._device.readU8(BME280_REGISTER_TEMP_DATA + 1)
    xlsb = self._device.readU8(BME280_REGISTER_TEMP_DATA + 2)
    raw = ((msb << 16) | (lsb << 8) | xlsb) >> 4
    return raw

  def read_raw_pressure(self):
    """Reads the raw (uncompensated) pressure level from the sensor."""
    """Assumes that the temperature has already been read """
    """i.e. that enough delay has been provided"""
    msb = self._device.readU8(BME280_REGISTER_PRESSURE_DATA)
    lsb = self._device.readU8(BME280_REGISTER_PRESSURE_DATA + 1)
    xlsb = self._device.readU8(BME280_REGISTER_PRESSURE_DATA + 2)
    raw = ((msb << 16) | (lsb << 8) | xlsb) >> 4
    return raw

  def read_raw_humidity(self):
    """Assumes that the temperature has already been read """
    """i.e. that enough delay has been provided"""
    msb = self._device.readU8(BME280_REGISTER_HUMIDITY_DATA)
    lsb = self._device.readU8(BME280_REGISTER_HUMIDITY_DATA + 1)
    raw = (msb << 8) | lsb
    return raw

  def read_temperature(self):
    """Get the compensated temperature in 0.01 of a degree celsius."""
    adc = self.read_raw_temp()
    var1 = ((adc >> 3) - (self.dig_T1 << 1)) * (self.dig_T2 >> 11)
    var2 = ((
        (((adc >> 4) - self.dig_T1) * ((adc >> 4) - self.dig_T1)) >> 12) *
        self.dig_T3) >> 14
    self.t_fine = var1 + var2
    return (self.t_fine * 5 + 128) >> 8

  def read_pressure(self):
    """Gets the compensated pressure in Pascals."""
    adc = self.read_raw_pressure()
    var1 = self.t_fine - 128000
    var2 = var1 * var1 * self.dig_P6
    var2 = var2 + ((var1 * self.dig_P5) << 17)
    var2 = var2 + (self.dig_P4 << 35)
    var1 = (((var1 * var1 * self.dig_P3) >> 8) +
            ((var1 * self.dig_P2) >> 12))
    var1 = (((1 << 47) + var1) * self.dig_P1) >> 33
    if var1 == 0:
      return 0
    p = 1048576 - adc
    p = (((p << 31) - var2) * 3125) // var1
    var1 = (self.dig_P9 * (p >> 13) * (p >> 13)) >> 25
    var2 = (self.dig_P8 * p) >> 19
    return ((p + var1 + var2) >> 8) + (self.dig_P7 << 4)

  def read_humidity(self):
    adc = self.read_raw_humidity()
    # print 'Raw humidity = {0:d}'.format (adc)
    h = self.t_fine - 76800
    h = (((((adc << 14) - (self.dig_H4 << 20) - (self.dig_H5 * h)) +
         16384) >> 15) * (((((((h * self.dig_H6) >> 10) * (((h *
                          self.dig_H3) >> 11) + 32768)) >> 10) + 2097152) *
                          self.dig_H2 + 8192) >> 14))
    h = h - (((((h >> 15) * (h >> 15)) >> 7) * self.dig_H1) >> 4)
    h = 0 if h < 0 else h
    h = 419430400 if h > 419430400 else h
    return h >> 12

  @property
  def temperature(self):
    "Return the temperature in degrees."
    t = self.read_temperature()
    ti = t // 100
    td = t - ti * 100
    return "{}.{:02d}C".format(ti, td)

  @property
  def pressure(self):
    "Return the temperature in hPa."
    p = self.read_pressure() // 256
    pi = p // 100
    pd = p - pi * 100
    return "{}.{:02d}hPa".format(pi, pd)

  @property
  def humidity(self):
    "Return the humidity in percent."
    h = self.read_humidity()
    hi = h // 1024
    hd = h * 100 // 1024 - hi * 100
    return "{}.{:02d}%".format(hi, hd)

View raw code

Regardless of the IDE you’re using, these are the general instructions to upload the BME280 library to your board:

  1. First, make sure your board is running MicroPython firmware—check the Prerequisites section.
  2. Create a new file in your IDE with the name BME280.py and paste the previous code there. Save that file.
  3. Establish a serial communication with your board using your IDE.
  4. Upload the BME280.py file to your board.
  5. At this point, the library should have been successfully uploaded to your board. Now, you can use the library functionalities in your code by importing the library: import BME280.

Sending Sensor Readings via Email – MicroPython – Code

Now you should have uploaded the umail.py, and BME280.py files to your board to be able to send emails and read from the BME280 sensor.

The following script sends a new email with the current sensor readings when the ESP32/ESP8266 board first boots/resets.

# Complete project details: https://RandomNerdTutorials.com/micropython-sensor-readings-email-esp32-esp826/
import umail # Micropython lib to send emails: https://github.com/shawwwn/uMail
import network
import BME280
from machine import Pin, SoftI2C

# Your network credentials
ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'

# Email details
sender_email = 'REPLACE_WITH_THE_SENDER_EMAIL'
sender_name = 'ESP32' #sender name
sender_app_password = 'REPLACE_WITH_THE_SENDER_EMAIL_APP_PASSWORD'
recipient_email ='REPLACE_WITH_THE_RECIPIENT_EMAIL'
email_subject ='BME280 Sensor Readings'

# BME280 pin assignment - ESP32
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000)
# BME280 pin assignment - ESP8266
#i2c = I2C(scl=Pin(5), sda=Pin(4), freq=10000)
bme = BME280.BME280(i2c=i2c)

def read_bme_sensor():
  try:
    temp = str(bme.temperature[:-1]) + " ºC"
    #uncomment for temperature in Fahrenheit
    #temp = str((bme.read_temperature()/100) * (9/5) + 32) + " 潞F"
    hum = str(bme.humidity[:-1]) + " %"
    pres = str(bme.pressure[:-3]) + " hPa"

    return temp, hum, pres
    #else:
    #  return('Invalid sensor readings.')
  except OSError as e:
    return('Failed to read sensor.')
  
def connect_wifi(ssid, password):
  #Connect to your network
  station = network.WLAN(network.STA_IF)
  station.active(True)
  station.connect(ssid, password)
  while station.isconnected() == False:
    pass
  print('Connection successful')
  print(station.ifconfig())
    
# Connect to your network
connect_wifi(ssid, password)

# Get sensor readings
temp, hum, pres = read_bme_sensor()
print(temp)
print(hum)
print(pres)

# Send the email
smtp = umail.SMTP('smtp.gmail.com', 465, ssl=True) # Gmail's SSL port
smtp.login(sender_email, sender_app_password)
smtp.to(recipient_email)
smtp.write("From:" + sender_name + "<"+ sender_email+">\n")
smtp.write("Subject:" + email_subject + "\n")
smtp.write("Temperature " + temp + "\n")
smtp.write("Humidity " + hum + "\n")
smtp.write("Pressure " + pres + "\n")
smtp.send()
smtp.quit()

View raw code

You need to insert your own details in the code before uploading the code to the board: SSID and password, sender email, sender name, and corresponding app password, recipient’s email, and email subject.

After inserting all your details you can upload the code to your board. The file with the code needs to be named main.py, otherwise, it will not work.

How the Code Works

Continue reading to learn how the code works, or skip to the Demonstration section.

Including Libraries

First, include the required libraries. The umail library, which we loaded previously to the board, so that we can send emails, and the network library so that we can set the ESP32/ESP8266 as a wi-fi station to be able to connect to the internet (local network). Additionally, you need to import the BME280 module to read from the BME280 sensor, and the Pin and I2C classes from the machine module to establish an I2C communication with the sensor.

import umail # Micropython lib to send emails: https://github.com/shawwwn/uMail
import network
import BME280
from machine import Pin, SoftI2C

Network Credentials

Insert your network credentials, SSID, and password, on the following variables so that your board can connect to the internet:

ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'

Email Details

Insert the email details: sender email, sender name, and corresponding app password. You really need to create an app password—using the regular email password won’t work, check these instructions.

# Email details
sender_email = 'REPLACE_WITH_THE_SENDER_EMAIL'
sender_name = 'ESP32' #sender name
sender_app_password = 'REPLACE_WITH_THE_SENDER_EMAIL_APP_PASSWORD'

Insert the recipient’s email on the recipient_email variable:

recipient_email ='REPLACE_WITH_THE_RECIPIENT_EMAIL'

BME280

The email subject is set to BME280 Sensor Readings, but you can change it on the email_subject variable.

email_subject ='BME280 Sensor Readings'

Create an i2c object using the board I2C pins. The ESP32 uses GPIO 22 and GPIO 21 as I2C pins.

i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000)

If you’re using an ESP8266 board, you should use GPIO 4 and GPIO 5 instead.

i2c = I2C(scl=Pin(5), sda=Pin(4), freq=10000)

If you’re using a board with different I2C pins, make sure that you modify this previous line.

Now that we have an i2c object, we can create a BME280 object (in this case called bme) on those pins.

bme = BME280.BME280(i2c=i2c)

Reading BME280: Temperature, Humidity, and Pressure

To read from the BME280 sensor, we created a function called read_bme_sensor() that returns the temperature, humidity, and pressure as strings with the corresponding units, which is the ideal format to use in the email body.

def read_bme_sensor():
  try:
    temp = str(bme.temperature[:-1]) + " ºC"
    #uncomment for temperature in Fahrenheit
    #temp = str((bme.read_temperature()/100) * (9/5) + 32) + " ºF"
    hum = str(bme.humidity[:-1]) + " %"
    pres = str(bme.pressure[:-3]) + " hPa"

    return temp, hum, pres
    #else:
    #  return('Invalid sensor readings.')
  except OSError as e:
    return('Failed to read sensor.')

By default, the function returns the temperature in Celcius degrees. If you want to get the temperature in Fahrenheit, you just need to uncomment the following line:

#temp = str((bme.read_temperature()/100) * (9/5) + 32) + " ºF"

Connecting to Wi-Fi

To connect the board to Wi-Fi, we created a function called connect_wifi() that accepts as arguments the SSID and password of the network you want to connect to. You should call this function later to actually connect the ESP board to the internet.

def connect_wifi(ssid, password):
  #Connect to your network
  station = network.WLAN(network.STA_IF)
  station.active(True)
  station.connect(ssid, password)
  while station.isconnected() == False:
    pass
  print('Connection successful')
  print(station.ifconfig())

Before sending the email, we need to connect the ESP32/ESP8266 to the internet, so call the connect_wifi() function (pass as arguments the ssid and password).

# Connect to your network
connect_wifi(ssid, password)

Getting New Readings

To get readings from the sensor in the format we want, we just need to call the read_bme_sensor() function we created previously. The temperature, humidity and pressure are saved on the temp, hum, and pres variables. These are string variables that already include the units (ºC, %, and hPa). The following lines, get the latest readings and print them on the shell.

# Get sensor readings
temp, hum, pres = read_bme_sensor()
print(temp)
print(hum)
print(pres)

Sending the Email

Now, we can finally start preparing and sending the email.

Start by creating an SMTP client using your email provider SMTP settings called smtp. Here we’re using a Gmail account. Change the settings if you’re using a different email provider—set the server, port, and if SSL is required or not.

smtp = umail.SMTP('smtp.gmail.com', 465, ssl=True) # Gmail's SSL port

Then, login into your account using the login() method on the smtp client—pass as arguments the email and corresponding app password.

smtp.login(sender_email, sender_app_password)

Set the recipient using the to() method and pass the recipient’s email as an argument:

smtp.to(recipient_email)

Then, use the write() method to write the email. You can use this method as follows to set the sender name.

smtp.write("From:" + sender_name + "<"+ sender_email+">\n")

And you can use the following line to set the email subject.

smtp.write("Subject:" + email_subject + "\n")

Finally, you can actually write your email content. We’re just sending the temperature, humidity, and pressure values in the email body, but you can add more text or even some HTML to format the email body. The write() method sends the email to the SMTP server.

smtp.write("Temperature " + temp + "\n")
smtp.write("Humidity " + hum + "\n")
smtp.write("Pressure " + pres + "\n")

If you need to send a long string as the email body, break the email message into smaller chunks and send each chunk using the write() method—see the uMail library documentation.

Finally, use the send() method to make the SMTP server send the email to the recipient.

smtp.send()

In the end, close the connection with the server using the quit() method.

smtp.quit()

Demonstration

After uploading the umail, and the BME280 modules, and the main.py script to your board, run the code or reset/restart your board. You should get a similar message in the shell indicating that your board connected successfully to the internet, and the current sensor readings.

Sensor readings via email micropython shell

After a while, you should receive a new email on the recipient’s email account.

email sent from EPS32 ESP8266 NodeMCU using MicroPython inbox

Open the email to check the current sensor readings.

BME280 sensor readings email Micropython

Wrapping Up

In this tutorial, you learned the basics of sending sensor readings via email with the ESP32/ESP8266 programmed with MicroPython firmware. As an example, we sent readings from a BME280 sensor, but you can easily modify the code to use a different sensor.

The example we’ve built sends the current sensor readings when the board resets/restarts. The idea is to add this feature to your own projects. For example, send sensor readings to your email every day, send the readings when they are above or below a certain threshold, send the readings when you click on a button… The possibilities are endless.

We hope you find this tutorial useful. If you want to use a different notification method, we have a tutorial showing how to send messages to WhatsApp using MicroPython (ESP32 and ESP8266):

You can check all our MicroPython projects here.

If you want to learn more about programming the ESP32 and ESP8266 boards with MicroPython, check out our eBook: MicroPython Programming with ESP32 and ESP8266.

Thanks for reading



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

3 thoughts on “MicroPython: Send Sensor Readings via email with the ESP32/ESP826 (BME280)”

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.