{"id":124613,"date":"2023-01-26T15:26:44","date_gmt":"2023-01-26T15:26:44","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=124613"},"modified":"2023-01-26T15:26:47","modified_gmt":"2023-01-26T15:26:47","slug":"micropython-send-emails-esp32-esp826","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/micropython-send-emails-esp32-esp826\/","title":{"rendered":"MicroPython: Send Emails with the ESP32\/ESP826"},"content":{"rendered":"\n<p>Learn how to program the ESP32 or ESP8266 NodeMCU boards with MicroPython to send emails using an SMTP server. This feature can be useful in your automation and IoT projects to send alert notifications, send messages with sensor readings, and much more.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" width=\"1200\" height=\"675\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/01\/ESP32-ESP8266-Send-Emails-Micropython.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"MicroPython Send Emails with the ESP32 ESP826 NodeMCU board\" class=\"wp-image-124622\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/01\/ESP32-ESP8266-Send-Emails-Micropython.jpg?w=1280&amp;quality=100&amp;strip=all&amp;ssl=1 1280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/01\/ESP32-ESP8266-Send-Emails-Micropython.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/01\/ESP32-ESP8266-Send-Emails-Micropython.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/01\/ESP32-ESP8266-Send-Emails-Micropython.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n<p>If you prefer to program your boards using Arduino IDE, you can check the following tutorials instead:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-send-email-smtp-server-arduino-ide\/\">ESP32 Send Emails using an SMTP Server: HTML, Text, and Attachments (Arduino IDE)<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/esp8266-nodemcu-send-email-smtp-server-arduino\/\">ESP8266 NodeMCU Send Emails using an SMTP Server: HTML, Text, and Attachments (Arduino)<\/a><\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"prerequisites\">Prerequisites<\/h2>\n\n\n\n<p class=\"rntbox rntclblue\">New to MicroPython? You can get started here: <a href=\"https:\/\/randomnerdtutorials.com\/getting-started-micropython-esp32-esp8266\/\">Getting Started with MicroPython on ESP32 and ESP8266<\/a>.<\/p>\n\n\n\n<p>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:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Thonny IDE:<ul><li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-thonny-micropython-python-ide-esp32-esp8266\/\">Installing and getting started with Thonny IDE<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/flashing-micropython-firmware-esptool-py-esp32-esp8266\/\">Flashing MicroPython Firmware with esptool.py<\/a><\/li><\/ul><\/li><li>uPyCraft IDE:<ul><li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-micropython-esp32-esp8266\/\">Getting Started with uPyCraft IDE<\/a><\/li><li>Install uPyCraft IDE (<a href=\"https:\/\/randomnerdtutorials.com\/install-upycraft-ide-windows-pc-instructions\/\">Windows<\/a>,&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/install-upycraft-ide-mac-os-x-instructions\/\">Mac OS X<\/a>,&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/install-upycraft-ide-linux-ubuntu-instructions\/\">Linux<\/a>)<\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/flash-upload-micropython-firmware-esp32-esp8266\/\">Flash\/Upload MicroPython Firmware to ESP32 and ESP8266<\/a><\/li><\/ul><\/li><\/ul>\n\n\n\n<p>Or, if you&#8217;re familiar with VS Code, you may want to use the PyMakr extension:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/micropython-esp32-esp8266-vs-code-pymakr\/\">MicroPython: Program ESP32\/ESP8266 using VS Code and Pymakr<\/a><\/li><\/ul>\n\n\n\n<p>For a comparison between different MicroPython IDEs, read: <a href=\"https:\/\/randomnerdtutorials.com\/micropython-ides-esp32-esp8266\/\">MicroPython IDEs for ESP32 and ESP8266<\/a>.<\/p>\n\n\n\n<p class=\"rntbox rntclblue\">Learn more about MicroPython:&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/micropython-programming-with-esp32-and-esp8266\/\">MicroPython Programming with ESP32 and ESP8266 eBook<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introducing SMTP Servers<\/h2>\n\n\n\n<p><strong>SMTP <\/strong>means <em>Simple Mail Transfer Protocol<\/em> and it is an internet standard for email transmission. To send emails using an ESP32 or ESP8266 board, you need to connect them to an SMTP Server.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">uMail Module<\/h3>\n\n\n\n<p>To easily send emails with MicroPython, we&#8217;ll use a module called <a href=\"https:\/\/github.com\/shawwwn\/uMail\" target=\"_blank\" rel=\"noopener\">uMail<\/a>. This module is not part of the standard collection of MicroPython libraries, so we&#8217;ll need to upload it separately to our board\u2014we&#8217;ll provide instructions for this later in the tutorial.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">SMTP Server Settings<\/h3>\n\n\n\n<p>To send emails with the ESP32 or ESP8266 boards, you need a sender email and you&#8217;ll need to know your email SMTP server settings. Below you&#8217;ll find the settings for the most popular email providers.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Gmail SMTP Server Settings<\/h4>\n\n\n\n<p>If you&#8217;re using a Gmail account, these are the SMTP Server details:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>SMTP Server: <strong>smtp.gmail.com<\/strong><\/li><li>SMTP username: Complete Gmail address<\/li><li>SMTP password: Your Gmail password<\/li><li>SMTP port (TLS): <strong>587<\/strong><\/li><li>SMTP port (SSL): <strong>465<\/strong><\/li><li>SMTP TLS\/SSL required: <strong>yes<\/strong><\/li><\/ul>\n\n\n\n<h4 class=\"wp-block-heading\">Outlook SMTP Server Settings<\/h4>\n\n\n\n<p>For Outlook accounts, these are the SMTP Server settings:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>SMTP Server: <strong>smtp.office365.com<\/strong><\/li><li>SMTP Username: Complete Outlook email address<\/li><li>SMTP Password: Your Outlook password<\/li><li>SMTP Port: <strong>587<\/strong><\/li><li>SMTP TLS\/SSL Required: <strong>Yes<\/strong><\/li><\/ul>\n\n\n\n<h4 class=\"wp-block-heading\">Live or Hotmail SMTP Server Settings<\/h4>\n\n\n\n<p>For Live or Hotmail accounts, these are the SMTP Server settings:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>SMTP Server: <strong>smtp.live.com<\/strong><\/li><li>SMTP Username: Complete Live\/Hotmail email address<\/li><li>SMTP Password: Your Windows Live Hotmail password<\/li><li>SMTP Port: <strong>587<\/strong><\/li><li>SMTP TLS\/SSL Required: <strong>Yes<\/strong><\/li><\/ul>\n\n\n\n<p>If you&#8217;re using another email provider, you need to search for its SMTP Server settings\u2014you&#8217;ll easily find them with a quick google search.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Sender Email (New Account)<\/h2>\n\n\n\n<p>We recommend creating a new email account to send the emails to your main personal email address. <strong>Do not use your main personal email to send emails via ESP32 or ESP8266<\/strong>. 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.<\/p>\n\n\n\n<p>We&#8217;ll use a newly created Gmail.com account to send the emails, but you can use any other email provider. The receiver email can be your personal email without any problem.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Create a Sender Email Account<\/h3>\n\n\n\n<p>Create a new email account for sending emails with the ESP32\/ESP8266. If you want to use a Gmail account, <a aria-label=\" (opens in a new tab)\" href=\"https:\/\/www.google.com\/gmail\/about\/\" target=\"_blank\" rel=\"noreferrer noopener\">go to this link<\/a> to create a new one.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"940\" height=\"602\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/02\/GMAIL-create-a-new-account.png?resize=940%2C602&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Gmail Create a new account\" class=\"wp-image-93593\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/02\/GMAIL-create-a-new-account.png?w=940&amp;quality=100&amp;strip=all&amp;ssl=1 940w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/02\/GMAIL-create-a-new-account.png?resize=300%2C192&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/02\/GMAIL-create-a-new-account.png?resize=768%2C492&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 940px) 100vw, 940px\" \/><\/figure><\/div>\n\n\n<h3 class=\"wp-block-heading\" id=\"create-app-password\">Create an App Password<\/h3>\n\n\n\n<p>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. <a href=\"https:\/\/support.google.com\/accounts\/answer\/185833\" target=\"_blank\" rel=\"noreferrer noopener\">Learn more about sign-in with app passwords here<\/a>.<\/p>\n\n\n\n<p>An app password can only be used with accounts that have <strong><a href=\"https:\/\/support.google.com\/accounts\/answer\/185839\" target=\"_blank\" rel=\"noopener\">2-step verification turned on<\/a><\/strong>. <\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Open your\u00a0<a href=\"https:\/\/myaccount.google.com\/\" target=\"_blank\" rel=\"noopener\">Google Account<\/a>.<\/li><li>In the navigation panel, select\u00a0<strong>Security<\/strong>.<\/li><li>Under \u201cSigning in to Google,\u201d select\u00a0<strong>2-Step Verification<\/strong>\u00a0> <strong>Get started<\/strong>.<\/li><li>Follow the on-screen steps.<\/li><\/ol>\n\n\n\n<p>After enabling 2-step verification, you can create an app password.<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Open your\u00a0<a href=\"https:\/\/myaccount.google.com\/\" target=\"_blank\" rel=\"noopener\">Google Account<\/a>.<\/li><li>In the navigation panel, select\u00a0<strong>Security<\/strong>.<\/li><li>Under \u201cSigning in to Google,\u201d select <strong>App Passwords<\/strong>.<\/li><\/ol>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"724\" height=\"323\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/create-app-password-gmail.png?resize=724%2C323&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Create app password gmail\" class=\"wp-image-109736\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/create-app-password-gmail.png?w=724&amp;quality=100&amp;strip=all&amp;ssl=1 724w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/create-app-password-gmail.png?resize=300%2C134&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 724px) 100vw, 724px\" \/><\/figure><\/div>\n\n\n<ol start=\"4\"><li>In the Select app field, choose <strong>mail<\/strong>. For the device, select <strong>Other<\/strong> and give it a name, for example <em>ESP32.<\/em> Then, click on <strong>Generate<\/strong>. It will pop-up a window with a password that you&#8217;ll use with the ESP32 or ESP8266 to send emails. Save that password (even though it says you won&#8217;t need to remember it) because you&#8217;ll need it later.<\/li><\/ol>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"654\" height=\"474\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/generated-app-password-gmail.png?resize=654%2C474&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Generated App password gmail\" class=\"wp-image-109742\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/generated-app-password-gmail.png?w=654&amp;quality=100&amp;strip=all&amp;ssl=1 654w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/generated-app-password-gmail.png?resize=300%2C217&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 654px) 100vw, 654px\" \/><\/figure><\/div>\n\n\n<p>Now, you should have an app password that you&#8217;ll use on the ESP32\/ESP8266 micropython script to send the emails.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"713\" height=\"515\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/Gmail-app-password-created-for-esp32-send-emails.png?resize=713%2C515&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Gmail app password created for ESP32 send emails\" class=\"wp-image-109740\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/Gmail-app-password-created-for-esp32-send-emails.png?w=713&amp;quality=100&amp;strip=all&amp;ssl=1 713w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/Gmail-app-password-created-for-esp32-send-emails.png?resize=300%2C217&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 713px) 100vw, 713px\" \/><\/figure><\/div>\n\n\n<p>If you&#8217;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 &#8220;<strong>your_email_provider<\/strong> + create app password&#8221;.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Uploading the uMail Module<\/h2>\n\n\n\n<p>To send the emails, we&#8217;ll use the uMail module. You can check its <a href=\"https:\/\/github.com\/shawwwn\/uMail\" target=\"_blank\" rel=\"noopener\">Github page and several examples here<\/a>. This library isn\u2019t 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 <span class=\"rnthl rntliteral\">umail.py<\/span>) before using the library.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Complete project details: https:\/\/RandomNerdTutorials.com\/micropython-send-emails-esp32-esp826\/\n# uMail (MicroMail) for MicroPython\n# Copyright (c) 2018 Shawwwn &lt;shawwwn1@gmai.com&gt; https:\/\/github.com\/shawwwn\/uMail\/blob\/master\/umail.py\n# License: MIT\nimport usocket\n\nDEFAULT_TIMEOUT = 10 # sec\nLOCAL_DOMAIN = '127.0.0.1'\nCMD_EHLO = 'EHLO'\nCMD_STARTTLS = 'STARTTLS'\nCMD_AUTH = 'AUTH'\nCMD_MAIL = 'MAIL'\nAUTH_PLAIN = 'PLAIN'\nAUTH_LOGIN = 'LOGIN'\n\nclass SMTP:\n    def cmd(self, cmd_str):\n        sock = self._sock;\n        sock.write('%s\\r\\n' % cmd_str)\n        resp = []\n        next = True\n        while next:\n            code = sock.read(3)\n            next = sock.read(1) == b'-'\n            resp.append(sock.readline().strip().decode())\n        return int(code), resp\n\n    def __init__(self, host, port, ssl=False, username=None, password=None):\n        import ssl\n        self.username = username\n        addr = usocket.getaddrinfo(host, port)[0][-1]\n        sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)\n        sock.settimeout(DEFAULT_TIMEOUT)\n        sock.connect(addr)\n        if ssl:\n            sock = ssl.wrap_socket(sock)\n        code = int(sock.read(3))\n        sock.readline()\n        assert code==220, 'cant connect to server %d, %s' % (code, resp)\n        self._sock = sock\n\n        code, resp = self.cmd(CMD_EHLO + ' ' + LOCAL_DOMAIN)\n        assert code==250, '%d' % code\n        if not ssl and CMD_STARTTLS in resp:\n            code, resp = self.cmd(CMD_STARTTLS)\n            assert code==220, 'start tls failed %d, %s' % (code, resp)\n            self._sock = ssl.wrap_socket(sock)\n\n        if username and password:\n            self.login(username, password)\n\n    def login(self, username, password):\n        self.username = username\n        code, resp = self.cmd(CMD_EHLO + ' ' + LOCAL_DOMAIN)\n        assert code==250, '%d, %s' % (code, resp)\n\n        auths = None\n        for feature in resp:\n            if feature[:4].upper() == CMD_AUTH:\n                auths = feature[4:].strip('=').upper().split()\n        assert auths!=None, &quot;no auth method&quot;\n\n        from ubinascii import b2a_base64 as b64\n        if AUTH_PLAIN in auths:\n            cren = b64(&quot;\\0%s\\0%s&quot; % (username, password))[:-1].decode()\n            code, resp = self.cmd('%s %s %s' % (CMD_AUTH, AUTH_PLAIN, cren))\n        elif AUTH_LOGIN in auths:\n            code, resp = self.cmd(&quot;%s %s %s&quot; % (CMD_AUTH, AUTH_LOGIN, b64(username)[:-1].decode()))\n            assert code==334, 'wrong username %d, %s' % (code, resp)\n            code, resp = self.cmd(b64(password)[:-1].decode())\n        else:\n            raise Exception(&quot;auth(%s) not supported &quot; % ', '.join(auths))\n\n        assert code==235 or code==503, 'auth error %d, %s' % (code, resp)\n        return code, resp\n\n    def to(self, addrs, mail_from=None):\n        mail_from = self.username if mail_from==None else mail_from\n        code, resp = self.cmd(CMD_EHLO + ' ' + LOCAL_DOMAIN)\n        assert code==250, '%d' % code\n        code, resp = self.cmd('MAIL FROM: &lt;%s&gt;' % mail_from)\n        assert code==250, 'sender refused %d, %s' % (code, resp)\n\n        if isinstance(addrs, str):\n            addrs = [addrs]\n        count = 0\n        for addr in addrs:\n            code, resp = self.cmd('RCPT TO: &lt;%s&gt;' % addr)\n            if code!=250 and code!=251:\n                print('%s refused, %s' % (addr, resp))\n                count += 1\n        assert count!=len(addrs), 'recipient refused, %d, %s' % (code, resp)\n\n        code, resp = self.cmd('DATA')\n        assert code==354, 'data refused, %d, %s' % (code, resp)\n        return code, resp\n\n    def write(self, content):\n        self._sock.write(content)\n\n    def send(self, content=''):\n        if content:\n            self.write(content)\n        self._sock.write('\\r\\n.\\r\\n') # the five letter sequence marked for ending\n        line = self._sock.readline()\n        return (int(line[:3]), line[4:].strip().decode())\n\n    def quit(self):\n        self.cmd(&quot;QUIT&quot;)\n        self._sock.close()\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP-MicroPython\/umail.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>Regardless of the IDE you&#8217;re using, these are the general instructions to upload the uMail library to your board:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>First, make sure your board is running MicroPython firmware\u2014check the <a href=\"#prerequisites\">Prerequisites section<\/a>.<\/li><li>Create a new file in your IDE with the name <span class=\"rnthl rntliteral\">umail.py<\/span> and paste the previous code there. Save that file.<\/li><li>Establish a serial communication with your board using your IDE.<\/li><li>Upload the <span class=\"rnthl rntliteral\">umail.py<\/span> file to your board.<\/li><li>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: <span class=\"rnthl rntliteral\">import umail<\/span>.<\/li><\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Sending Emails with the ESP32\/ESP8266 (MicroPython) &#8211; Code<\/h2>\n\n\n\n<p>At this point, you should have uploaded the <span class=\"rnthl rntliteral\">umail.py<\/span> file to your board to be able to send emails using the <span class=\"rnthl rntliteral\">umail<\/span> module. <\/p>\n\n\n\n<p>The following script sends a simple email when the ESP32\/ESP8266 board first boots\/resets.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Complete project details: https:\/\/RandomNerdTutorials.com\/micropython-send-emails-esp32-esp826\/\n# Micropython lib to send emails: https:\/\/github.com\/shawwwn\/uMail\nimport umail\nimport network\n\n# Your network credentials\nssid = 'REPLACE_WITH_YOUR_SSID'\npassword = 'REPLACE_WITH_YOUR_PASSWORD'\n\n# Email details\nsender_email = 'REPLACE_WITH_THE_SENDER_EMAIL'\nsender_name = 'ESP32' #sender name\nsender_app_password = 'REPLACE_WITH_THE_SENDER_EMAIL_APP_PASSWORD'\nrecipient_email ='REPLACE_WITH_THE_RECIPIENT_EMAIL'\nemail_subject ='Test Email'\n\ndef connect_wifi(ssid, password):\n  #Connect to your network\n  station = network.WLAN(network.STA_IF)\n  station.active(True)\n  station.connect(ssid, password)\n  while station.isconnected() == False:\n    pass\n  print('Connection successful')\n  print(station.ifconfig())\n    \n# Connect to your network\nconnect_wifi(ssid, password)\n\n# Send the email\nsmtp = umail.SMTP('smtp.gmail.com', 465, ssl=True) # Gmail's SSL port\nsmtp.login(sender_email, sender_app_password)\nsmtp.to(recipient_email)\nsmtp.write(&quot;From:&quot; + sender_name + &quot;&lt;&quot;+ sender_email+&quot;&gt;\\n&quot;)\nsmtp.write(&quot;Subject:&quot; + email_subject + &quot;\\n&quot;)\nsmtp.write(&quot;Hello from ESP32&quot;)\nsmtp.send()\nsmtp.quit()\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP-MicroPython\/esp_send_email_smtp.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>You need to insert your details on the code before uploading the code to the board: SSID and password, sender email, sender name, and corresponding app password, recipient&#8217;s email, and email subject.<\/p>\n\n\n\n<p>After inserting all your details you can upload the code to your board. The file with the code needs to be named <span class=\"rnthl rntliteral\">main.py<\/span>, otherwise, it will not work.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How the Code Works<\/h3>\n\n\n\n<p>First, include the required libraries. The <span class=\"rnthl rntliteral\">umail<\/span> library, which we loaded previously to the board, so that we can send emails, and the <span class=\"rnthl rntliteral\">network<\/span> library so that we can set the ESP32\/ESP8266 as a wi-fi station to be able to connect to the internet (local network).<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>import umail # Micropython lib to send emails: https:\/\/github.com\/shawwwn\/uMail\nimport network<\/code><\/pre>\n\n\n\n<p>Insert your network credentials, SSID and password, on the following variables so that your board can connect to the internet:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>ssid = 'REPLACE_WITH_YOUR_SSID'\npassword = 'REPLACE_WITH_YOUR_PASSWORD'<\/code><\/pre>\n\n\n\n<p>Insert the email details: sender email, sender name, and corresponding app password. You really need to create an app password\u2014using the regular email password won&#8217;t work, <a href=\"#create-app-password\">see this section<\/a>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Email details\nsender_email = 'REPLACE_WITH_THE_SENDER_EMAIL'\nsender_name = 'ESP32' #sender name\nsender_app_password = 'REPLACE_WITH_THE_SENDER_EMAIL_APP_PASSWORD'<\/code><\/pre>\n\n\n\n<p>Insert the recipient&#8217;s email on the <span class=\"rnthl rntliteral\">recipient_email<\/span> variable:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>recipient_email ='REPLACE_WITH_THE_RECIPIENT_EMAIL'<\/code><\/pre>\n\n\n\n<p>The email subject is set to <span class=\"rnthl rntliteral\">Test Email<\/span>, but you can change it on the <span class=\"rnthl rntliteral\">email_subject<\/span> variable.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>email_subject ='Test Email'<\/code><\/pre>\n\n\n\n<p>We created a function called <span class=\"rnthl rntliteral\">connect_wifi()<\/span> 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.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def connect_wifi(ssid, password):\n  #Connect to your network\n  station = network.WLAN(network.STA_IF)\n  station.active(True)\n  station.connect(ssid, password)\n  while station.isconnected() == False:\n    pass\n  print('Connection successful')\n  print(station.ifconfig())<\/code><\/pre>\n\n\n\n<p>Before sending the email, we need to connect the ESP32\/ESP8266 to the internet, so call the <span class=\"rnthl rntliteral\">connect_wifi()<\/span> function (pass as arguments the ssid and password).<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Connect to your network\nconnect_wifi(ssid, password)<\/code><\/pre>\n\n\n\n<p>Now, we can finally start preparing and sending the email.<\/p>\n\n\n\n<p>Start by creating an SMTP client using your email provider SMTP settings called <span class=\"rnthl rntliteral\">smtp<\/span>. Here we&#8217;re using a Gmail account. Change the settings if you&#8217;re using a different email provider\u2014set the server, port, and if SSL is required or not.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>smtp = umail.SMTP('smtp.gmail.com', 465, ssl=True) # Gmail's SSL port<\/code><\/pre>\n\n\n\n<p>Then, login into your account using the <span class=\"rnthl rntliteral\">login()<\/span> method on the <span class=\"rnthl rntliteral\">smtp<\/span> client\u2014pass as arguments the email and corresponding app password.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>smtp.login(sender_email, sender_app_password)<\/code><\/pre>\n\n\n\n<p>Set the recipient using the <span class=\"rnthl rntliteral\">to()<\/span> method and pass the recipient&#8217;s email as an argument:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>smtp.to(recipient_email)<\/code><\/pre>\n\n\n\n<p>Then, use the <span class=\"rnthl rntliteral\">write()<\/span> method to write the email. You can use this method as follows to set the sender name.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>smtp.write(\"From:\" + sender_name + \"&lt;\"+ sender_email+\">\\n\")<\/code><\/pre>\n\n\n\n<p>And you can use the following line to set the email subject.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>smtp.write(\"Subject:\" + email_subject + \"\\n\")<\/code><\/pre>\n\n\n\n<p>Finally, you can actually write your email content. This is just a test email. We&#8217;re setting the message to &#8220;Hello from the ESP32\/ESP8266&#8221; board. The <span class=\"rnthl rntliteral\">write()<\/span> method sends the email to the SMTP server.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>smtp.write(\"Hello from the ESP32\/ESP8266\")<\/code><\/pre>\n\n\n\n<p>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 <span class=\"rnthl rntliteral\">write()<\/span> method\u2014<a href=\"https:\/\/github.com\/shawwwn\/uMail#api-docs\" target=\"_blank\" rel=\"noopener\">see the uMail library documentation<\/a>.<\/p>\n\n\n\n<p>Finally, use the <span class=\"rnthl rntliteral\">send()<\/span> method to make the SMTP server send the email to the recipient.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>smtp.send()<\/code><\/pre>\n\n\n\n<p>In the end, close the connection with the server using the <span class=\"rnthl rntliteral\">quit()<\/span> method.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>smtp.quit()<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Demonstration<\/h2>\n\n\n\n<p>After uploading the <span class=\"rnthl rntliteral\">umail<\/span> module and the <span class=\"rnthl rntliteral\">main.py<\/span> 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.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><a href=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/01\/micropython-connection-successful.png?quality=100&#038;strip=all&#038;ssl=1\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"638\" height=\"168\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/01\/micropython-connection-successful.png?resize=638%2C168&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"micropython internet connection successful\" class=\"wp-image-124615\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/01\/micropython-connection-successful.png?w=638&amp;quality=100&amp;strip=all&amp;ssl=1 638w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/01\/micropython-connection-successful.png?resize=300%2C79&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 638px) 100vw, 638px\" \/><\/a><\/figure><\/div>\n\n\n<p>After a while, you should receive a new email on the recipient&#8217;s email account.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"905\" height=\"254\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/01\/Email-received-micropython.jpg?resize=905%2C254&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"test email sent from EPS32\/ESP8266 using MicroPython (inbox)\" class=\"wp-image-124617\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/01\/Email-received-micropython.jpg?w=905&amp;quality=100&amp;strip=all&amp;ssl=1 905w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/01\/Email-received-micropython.jpg?resize=300%2C84&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/01\/Email-received-micropython.jpg?resize=768%2C216&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 905px) 100vw, 905px\" \/><\/figure><\/div>\n\n\n<p>Open the email to check its content.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"597\" height=\"267\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/01\/Email-received-micropython-2.jpg?resize=597%2C267&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"test email sent from EPS32\/ESP8266 using MicroPython\" class=\"wp-image-124619\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/01\/Email-received-micropython-2.jpg?w=597&amp;quality=100&amp;strip=all&amp;ssl=1 597w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/01\/Email-received-micropython-2.jpg?resize=300%2C134&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 597px) 100vw, 597px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>In this tutorial, you learned how to send emails with the ESP32\/ESP8266 using MicroPython firmware. Sending an email using an SMTP server is very straightforward thanks to the <a href=\"https:\/\/github.com\/shawwwn\/uMail\" target=\"_blank\" rel=\"noopener\">uMail Micropython module<\/a>.<\/p>\n\n\n\n<p>We&#8217;ve shown you a simple example application. Now, the idea is to use this feature in your own projects. This can be useful to send notification alerts, sensor readings, and other applications.<\/p>\n\n\n\n<p>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):<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/micropython-whatsapp-esp32-esp826\/\" title=\"MicroPython: Send Messages to WhatsApp with the ESP32\/ESP826\">MicroPython: Send Messages to WhatsApp with the ESP32\/ESP826<\/a><\/li><\/ul>\n\n\n\n<p>You can check all our&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/projects-esp32-esp8266-micropython\/\">MicroPython projects here<\/a>.<\/p>\n\n\n\n<p>If you want to learn more about programming the ESP32 and ESP8266 boards with MicroPython, check out our eBook:&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/micropython-programming-with-esp32-and-esp8266\/\"><strong>MicroPython Programming with ESP32 and ESP8266<\/strong><\/a><strong>.<\/strong><\/p>\n\n\n\n<p>Thanks for reading<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to program the ESP32 or ESP8266 NodeMCU boards with MicroPython to send emails using an SMTP server. This feature can be useful in your automation and IoT projects &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"MicroPython: Send Emails with the ESP32\/ESP826\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/micropython-send-emails-esp32-esp826\/#more-124613\" aria-label=\"Read more about MicroPython: Send Emails with the ESP32\/ESP826\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":124622,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[310,309,264],"tags":[],"class_list":["post-124613","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-micropython","category-0-esp32-micropython","category-project"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/01\/ESP32-ESP8266-Send-Emails-Micropython.jpg?fit=1280%2C720&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/124613","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=124613"}],"version-history":[{"count":9,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/124613\/revisions"}],"predecessor-version":[{"id":126273,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/124613\/revisions\/126273"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/124622"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=124613"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=124613"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=124613"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}