{"id":150280,"date":"2024-04-30T17:44:25","date_gmt":"2024-04-30T17:44:25","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=150280"},"modified":"2024-04-30T18:16:31","modified_gmt":"2024-04-30T18:16:31","slug":"raspberry-pi-pico-w-send-email-micropython","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-send-email-micropython\/","title":{"rendered":"Raspberry Pi Pico W: Sending Emails using SMTP Server (MicroPython)"},"content":{"rendered":"\n<p>Learn how to send emails with the Raspberry Pi Pico 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. We&#8217;ll program the Raspberry Pi Pico using MicroPython firmware.<\/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\/2024\/03\/Raspberry-Pi-Pico-Sending-Email-MicroPython.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico W Sending Emails using SMTP Server MicroPython\" class=\"wp-image-150406\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-Pi-Pico-Sending-Email-MicroPython.jpg?w=1920&amp;quality=100&amp;strip=all&amp;ssl=1 1920w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-Pi-Pico-Sending-Email-MicroPython.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-Pi-Pico-Sending-Email-MicroPython.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-Pi-Pico-Sending-Email-MicroPython.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-Pi-Pico-Sending-Email-MicroPython.jpg?resize=1536%2C864&amp;quality=100&amp;strip=all&amp;ssl=1 1536w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n<p><strong>New to the Raspberry Pi Pico?<\/strong> <a href=\"https:\/\/randomnerdtutorials.com\/getting-started-raspberry-pi-pico-w\/\" title=\"\">Get started with the Raspberry Pi Pico here<\/a>.<\/p>\n\n\n\n<p><strong>Table of Contents:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"#prerequisites\" title=\"\">Prerequisites &#8211; MicroPython Firmware<\/a><\/li>\n\n\n\n<li><a href=\"#smtp-server\" title=\"\">Introducing SMTP Servers<\/a><\/li>\n\n\n\n<li><a href=\"#sender-email-account\" title=\"\">Sender Email Account<\/a><\/li>\n\n\n\n<li><a href=\"#create-app-password\" title=\"\">Create an App Password<\/a><\/li>\n\n\n\n<li><a href=\"#umail-module\" title=\"\">The umail Module<\/a><\/li>\n\n\n\n<li><a href=\"#send-email-pico-micropython\" title=\"\">Sending Emails with the Raspberry Pi Pico (MicroPython) &#8211; Code<\/a><\/li>\n\n\n\n<li><a href=\"#demonstration\" title=\"\">Testing the Code<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"prerequisites\">Prerequisites &#8211; MicroPython Firmware<\/h2>\n\n\n\n<p>To follow this tutorial you need MicroPython firmware installed in your Raspberry Pi Pico board. You also need an IDE to write and upload the code to your board. <\/p>\n\n\n\n<p>The recommended MicroPython IDE for the Raspberry Pi Pico is Thonny IDE. Follow the next tutorial to learn how to install Thonny IDE, flash MicroPython firmware, and upload code to the board.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-raspberry-pi-pico-w\/#install-thonny-ide\" title=\"\">Programming Raspberry Pi Pico using MicroPython<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"smtp-server\">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 the Raspberry Pi Pico, you need to connect it 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 Raspberry Pi Pico, 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\">\n<li>SMTP Server: <strong>smtp.gmail.com<\/strong><\/li>\n\n\n\n<li>SMTP username: Complete Gmail address<\/li>\n\n\n\n<li>SMTP password: Your Gmail password<\/li>\n\n\n\n<li>SMTP port (TLS): <strong>587<\/strong><\/li>\n\n\n\n<li>SMTP port (SSL): <strong>465<\/strong><\/li>\n\n\n\n<li>SMTP TLS\/SSL required: <strong>yes<\/strong><\/li>\n<\/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\">\n<li>SMTP Server: <strong>smtp.office365.com<\/strong><\/li>\n\n\n\n<li>SMTP Username: Complete Outlook email address<\/li>\n\n\n\n<li>SMTP Password: Your Outlook password<\/li>\n\n\n\n<li>SMTP Port: <strong>587<\/strong><\/li>\n\n\n\n<li>SMTP TLS\/SSL Required: <strong>Yes<\/strong><\/li>\n<\/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\">\n<li>SMTP Server: <strong>smtp.live.com<\/strong><\/li>\n\n\n\n<li>SMTP Username: Complete Live\/Hotmail email address<\/li>\n\n\n\n<li>SMTP Password: Your Windows Live Hotmail password<\/li>\n\n\n\n<li>SMTP Port: <strong>587<\/strong><\/li>\n\n\n\n<li>SMTP TLS\/SSL Required: <strong>Yes<\/strong><\/li>\n<\/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\" id=\"sender-email-account\">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 the Raspberry Pi Pico<\/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 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 Raspberry Pi Pico. 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=\"946\" height=\"667\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/create-gmail-account.png?resize=946%2C667&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Gmail Create a new account\" class=\"wp-image-150281\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/create-gmail-account.png?w=946&amp;quality=100&amp;strip=all&amp;ssl=1 946w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/create-gmail-account.png?resize=300%2C212&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/create-gmail-account.png?resize=768%2C541&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 946px) 100vw, 946px\" \/><\/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\">\n<li>Open your&nbsp;<a href=\"https:\/\/myaccount.google.com\/\" target=\"_blank\" rel=\"noopener\">Google Account<\/a>.<\/li>\n\n\n\n<li>In the navigation panel, select&nbsp;<strong>Security<\/strong>.<\/li>\n\n\n\n<li>Under \u201cSigning in to Google,\u201d select&nbsp;<strong>2-Step Verification<\/strong>&nbsp;&gt; <strong>Get started<\/strong>.<\/li>\n\n\n\n<li>Follow the on-screen steps.<\/li>\n<\/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\">\n<li>Open your&nbsp;<a href=\"https:\/\/myaccount.google.com\/\" target=\"_blank\" rel=\"noopener\">Google Account<\/a>.<\/li>\n\n\n\n<li>In the search bar, search for <strong>App Password<\/strong>.<\/li>\n\n\n\n<li>Click on the <strong>App Passwords<\/strong> menu.<\/li>\n<\/ol>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"756\" height=\"477\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/gmail-app-password.png?resize=756%2C477&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Gmail create app password menu\" class=\"wp-image-150282\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/gmail-app-password.png?w=756&amp;quality=100&amp;strip=all&amp;ssl=1 756w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/gmail-app-password.png?resize=300%2C189&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 756px) 100vw, 756px\" \/><\/figure><\/div>\n\n\n<ol start=\"4\"><li>Now, you can create a new app password to use with the Raspberry Pi Pico. Give it a name. For example: Pi Pico.<\/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=\"671\" height=\"699\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/create-new-app-password-rpi-pico-f.png?resize=671%2C699&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Gmail, create new app password, rpi pico\" class=\"wp-image-150284\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/create-new-app-password-rpi-pico-f.png?w=671&amp;quality=100&amp;strip=all&amp;ssl=1 671w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/create-new-app-password-rpi-pico-f.png?resize=288%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 288w\" sizes=\"(max-width: 671px) 100vw, 671px\" \/><\/figure><\/div>\n\n\n<p>Click <strong>Create<\/strong>. Your app password will show up. Copy it to a safe place because you&#8217;ll need it later (even though it says you don&#8217;t need to).<\/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=\"542\" height=\"454\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/generated-app-password.png?resize=542%2C454&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Generated app password\" class=\"wp-image-150285\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/generated-app-password.png?w=542&amp;quality=100&amp;strip=all&amp;ssl=1 542w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/generated-app-password.png?resize=300%2C251&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 542px) 100vw, 542px\" \/><\/figure><\/div>\n\n\n<p>Now, you should have an app password that you&#8217;ll use on the Raspberry Pi Pico 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=\"643\" height=\"525\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/app-password-create-for-Rpi-Pico-Gmail.png?resize=643%2C525&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"App password created for the Raspberry Pi Pico Gmail\" class=\"wp-image-150286\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/app-password-create-for-Rpi-Pico-Gmail.png?w=643&amp;quality=100&amp;strip=all&amp;ssl=1 643w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/app-password-create-for-Rpi-Pico-Gmail.png?resize=300%2C245&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 643px) 100vw, 643px\" \/><\/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\" id=\"umail-module\">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<\/a>. This library isn\u2019t part of the standard MicroPython library by default. So, you need to upload the following file to your Raspberry Pi Pico (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\/raspberry-pi-pico-w-send-email-micropython\/\r\n# uMail (MicroMail) for MicroPython Copyright (c) 2018 Shawwwn &lt;shawwwn1@gmai.com&gt; https:\/\/github.com\/shawwwn\/uMail\/blob\/master\/umail.py License: MIT\r\nimport usocket\r\n\r\nDEFAULT_TIMEOUT = 10 # sec\r\nLOCAL_DOMAIN = '127.0.0.1'\r\nCMD_EHLO = 'EHLO'\r\nCMD_STARTTLS = 'STARTTLS'\r\nCMD_AUTH = 'AUTH'\r\nCMD_MAIL = 'MAIL'\r\nAUTH_PLAIN = 'PLAIN'\r\nAUTH_LOGIN = 'LOGIN'\r\n\r\nclass SMTP:\r\n    def cmd(self, cmd_str):\r\n        sock = self._sock;\r\n        sock.write('%s\\r\\n' % cmd_str)\r\n        resp = []\r\n        next = True\r\n        while next:\r\n            code = sock.read(3)\r\n            next = sock.read(1) == b'-'\r\n            resp.append(sock.readline().strip().decode())\r\n        return int(code), resp\r\n\r\n    def __init__(self, host, port, ssl=False, username=None, password=None):\r\n        import ssl\r\n        self.username = username\r\n        addr = usocket.getaddrinfo(host, port)[0][-1]\r\n        sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)\r\n        sock.settimeout(DEFAULT_TIMEOUT)\r\n        sock.connect(addr)\r\n        if ssl:\r\n            sock = ssl.wrap_socket(sock)\r\n        code = int(sock.read(3))\r\n        sock.readline()\r\n        assert code==220, 'cant connect to server %d, %s' % (code, resp)\r\n        self._sock = sock\r\n\r\n        code, resp = self.cmd(CMD_EHLO + ' ' + LOCAL_DOMAIN)\r\n        assert code==250, '%d' % code\r\n        if not ssl and CMD_STARTTLS in resp:\r\n            code, resp = self.cmd(CMD_STARTTLS)\r\n            assert code==220, 'start tls failed %d, %s' % (code, resp)\r\n            self._sock = ssl.wrap_socket(sock)\r\n\r\n        if username and password:\r\n            self.login(username, password)\r\n\r\n    def login(self, username, password):\r\n        self.username = username\r\n        code, resp = self.cmd(CMD_EHLO + ' ' + LOCAL_DOMAIN)\r\n        assert code==250, '%d, %s' % (code, resp)\r\n\r\n        auths = None\r\n        for feature in resp:\r\n            if feature[:4].upper() == CMD_AUTH:\r\n                auths = feature[4:].strip('=').upper().split()\r\n        assert auths!=None, &quot;no auth method&quot;\r\n\r\n        from ubinascii import b2a_base64 as b64\r\n        if AUTH_PLAIN in auths:\r\n            cren = b64(&quot;\\0%s\\0%s&quot; % (username, password))[:-1].decode()\r\n            code, resp = self.cmd('%s %s %s' % (CMD_AUTH, AUTH_PLAIN, cren))\r\n        elif AUTH_LOGIN in auths:\r\n            code, resp = self.cmd(&quot;%s %s %s&quot; % (CMD_AUTH, AUTH_LOGIN, b64(username)[:-1].decode()))\r\n            assert code==334, 'wrong username %d, %s' % (code, resp)\r\n            code, resp = self.cmd(b64(password)[:-1].decode())\r\n        else:\r\n            raise Exception(&quot;auth(%s) not supported &quot; % ', '.join(auths))\r\n\r\n        assert code==235 or code==503, 'auth error %d, %s' % (code, resp)\r\n        return code, resp\r\n\r\n    def to(self, addrs, mail_from=None):\r\n        mail_from = self.username if mail_from==None else mail_from\r\n        code, resp = self.cmd(CMD_EHLO + ' ' + LOCAL_DOMAIN)\r\n        assert code==250, '%d' % code\r\n        code, resp = self.cmd('MAIL FROM: &lt;%s&gt;' % mail_from)\r\n        assert code==250, 'sender refused %d, %s' % (code, resp)\r\n\r\n        if isinstance(addrs, str):\r\n            addrs = [addrs]\r\n        count = 0\r\n        for addr in addrs:\r\n            code, resp = self.cmd('RCPT TO: &lt;%s&gt;' % addr)\r\n            if code!=250 and code!=251:\r\n                print('%s refused, %s' % (addr, resp))\r\n                count += 1\r\n        assert count!=len(addrs), 'recipient refused, %d, %s' % (code, resp)\r\n\r\n        code, resp = self.cmd('DATA')\r\n        assert code==354, 'data refused, %d, %s' % (code, resp)\r\n        return code, resp\r\n\r\n    def write(self, content):\r\n        self._sock.write(content)\r\n\r\n    def send(self, content=''):\r\n        if content:\r\n            self.write(content)\r\n        self._sock.write('\\r\\n.\\r\\n') # the five letter sequence marked for ending\r\n        line = self._sock.readline()\r\n        return (int(line[:3]), line[4:].strip().decode())\r\n\r\n    def quit(self):\r\n        self.cmd(&quot;QUIT&quot;)\r\n        self._sock.close()\r\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi-Pico\/MicroPython\/email\/umail.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Create a new file in Thonny IDE and paste the previous code;<\/li>\n\n\n\n<li>Go to <strong>File<\/strong> &gt; <strong>Save as&#8230;<\/strong> and select Raspberry Pi Pico;<\/li>\n\n\n\n<li>Save the file with the name <strong><em>umail.py<\/em><\/strong> (don&#8217;t change the name).<\/li>\n<\/ol>\n\n\n\n<p>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>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"send-email-pico-micropython\">Sending Emails with the Raspberry Pi Pico (MicroPython) &#8211; Code<\/h2>\n\n\n\n<p>The following MicroPython script sends a simple email when the Raspberry Pi Pico board first boots\/resets.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Rui Santos &amp; Sara Santos - Random Nerd Tutorials\r\n# Complete project details at https:\/\/RandomNerdTutorials.com\/raspberry-pi-pico-w-send-email-micropython\/\r\n# Micropython lib to send emails: https:\/\/github.com\/shawwwn\/uMail\r\nimport umail\r\nimport network\r\nimport time\r\n\r\n# Your network credentials\r\nssid = 'REPLACE_WITH_YOUR_SSID'\r\npassword = 'REPLACE_WITH_YOUR_PASSWORD'\r\n\r\n# Email details\r\nsender_email = 'REPLACE_WITH_THE_SENDER_EMAIL'\r\nsender_name = 'Raspberry Pi Pico'\r\nsender_app_password = 'REPLACE_WITH_THE_SENDER_EMAIL_APP_PASSWORD'\r\nrecipient_email ='REPLACE_WITH_THE_RECIPIENT_EMAIL'\r\nemail_subject ='Hello from RPi Pico W'\r\n\r\n# Init Wi-Fi Interface\r\ndef init_wifi(ssid, password):\r\n    wlan = network.WLAN(network.STA_IF)\r\n    wlan.active(True)\r\n    # Connect to your network\r\n    wlan.connect(ssid, password)\r\n    # Wait for Wi-Fi connection\r\n    connection_timeout = 10\r\n    while connection_timeout &gt; 0:\r\n        print(wlan.status())\r\n        if wlan.status() &gt;= 3:\r\n            break\r\n        connection_timeout -= 1\r\n        print('Waiting for Wi-Fi connection...')\r\n        time.sleep(1)\r\n    # Check if connection is successful\r\n    if wlan.status() != 3:\r\n        print('Failed to connect to Wi-Fi')\r\n        return False\r\n    else:\r\n        print('Connection successful!')\r\n        network_info = wlan.ifconfig()\r\n        print('IP address:', network_info[0])\r\n        return True\r\n    \r\n# Connect to your network\r\ninit_wifi(ssid, password)\r\n\r\n# Send the email\r\nsmtp = umail.SMTP('smtp.gmail.com', 465, ssl=True) # Gmail's SSL port\r\n\r\ntry:\r\n    smtp.login(sender_email, sender_app_password)\r\n    smtp.to(recipient_email)\r\n    smtp.write(&quot;From:&quot; + sender_name + &quot;&lt;&quot;+ sender_email+&quot;&gt;\\n&quot;)\r\n    smtp.write(&quot;Subject:&quot; + email_subject + &quot;\\n&quot;)\r\n    smtp.write(&quot;Hello from the Raspberry Pi Pico. Testing.&quot;)\r\n    smtp.send()\r\n    print(&quot;Email Sent Successfully&quot;)\r\n    \r\nexcept Exception as e:\r\n    print(&quot;Failed to send email:&quot;, e)\r\nfinally:\r\n    smtp.quit()<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi-Pico\/MicroPython\/email\/Send_Email_Basic.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 <strong>app password<\/strong> (it&#8217;s the <a href=\"#create-app-password\" title=\"\">app password<\/a> not the email password), recipient&#8217;s email, and email subject.<\/p>\n\n\n\n<p>After inserting all your details you can run the code to test it. If you want the code to run without being connected to your computer, you need to save it on the Raspberry Pi Pico with the name <strong><em>main.py<\/em><\/strong>.<\/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 Pico, so that we can send emails, and the <span class=\"rnthl rntliteral\">network<\/span> library so that we can set the Pico as a wi-fi station to connect to the internet (local network).<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>import 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 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 = 'Raspberry Pi Pico'\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\">Hello from RPi Pico W<\/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 ='Hello from RPi Pico W'<\/code><\/pre>\n\n\n\n<p>We created a function called <span class=\"rnthl rntliteral\">init_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 connect the Pico board to the internet.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Init Wi-Fi Interface\ndef init_wifi(ssid, password):\n    wlan = network.WLAN(network.STA_IF)\n    wlan.active(True)\n    # Connect to your network\n    wlan.connect(ssid, password)\n    # Wait for Wi-Fi connection\n    connection_timeout = 10\n    while connection_timeout &gt; 0:\n        print(wlan.status())\n        if wlan.status() &gt;= 3:\n            break\n        connection_timeout -= 1\n        print('Waiting for Wi-Fi connection...')\n        time.sleep(1)\n    # Check if connection is successful\n    if wlan.status() != 3:\n        print('Failed to connect to Wi-Fi')\n        return False\n    else:\n        print('Connection successful!')\n        network_info = wlan.ifconfig()\n        print('IP address:', network_info&#091;0])\n        return True<\/code><\/pre>\n\n\n\n<p>Before sending the email, we need to connect the Raspberry Pi Pico to the internet, so call the <span class=\"rnthl rntliteral\">init_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\ninit_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>We then have <span class=\"rnthl rntliteral\">try<\/span> and <span class=\"rnthl rntliteral\">except<\/span> statements to send the email or print an error message if it fails.<\/p>\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+\"&gt;\\n\")<\/code><\/pre>\n\n\n\n<p>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 write your email content. This is just a test email. We&#8217;re setting the message to &#8220;Hello from the Raspberry Pi Pico. Testing.&#8221;. 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 Raspberry Pi Pico. Testing.\")<\/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>If it fails to send the email, it will print an error message:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>except Exception as e:\n    print(\"Failed to send email:\", e)<\/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>finally:\n    smtp.quit()<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"demonstration\">Demonstration<\/h2>\n\n\n\n<p>After uploading the <span class=\"rnthl rntliteral\">umail.py<\/span> module, you can run our sample code to test sending an email.<\/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=\"470\" height=\"114\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/thonny-ide-run-button.png?resize=470%2C114&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Run MicroPython script Thonny IDE\" class=\"wp-image-144594\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/thonny-ide-run-button.png?w=470&amp;quality=100&amp;strip=all&amp;ssl=1 470w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/12\/thonny-ide-run-button.png?resize=300%2C73&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 470px) 100vw, 470px\" \/><\/figure><\/div>\n\n\n<p>The Pico should connect to the internet and send the email.<\/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=\"683\" height=\"298\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/email-sent-successfully.png?resize=683%2C298&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico Send Email Successfully\" class=\"wp-image-150400\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/email-sent-successfully.png?w=683&amp;quality=100&amp;strip=all&amp;ssl=1 683w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/email-sent-successfully.png?resize=300%2C131&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 683px) 100vw, 683px\" \/><\/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=\"1037\" height=\"304\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Received-email-raspberry-pi-pico.jpg?resize=1037%2C304&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"test email sent from Raspberry Pi Pico using MicroPython (inbox)\" class=\"wp-image-150402\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Received-email-raspberry-pi-pico.jpg?w=1037&amp;quality=100&amp;strip=all&amp;ssl=1 1037w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Received-email-raspberry-pi-pico.jpg?resize=300%2C88&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Received-email-raspberry-pi-pico.jpg?resize=1024%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Received-email-raspberry-pi-pico.jpg?resize=768%2C225&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 1037px) 100vw, 1037px\" \/><\/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=\"553\" height=\"290\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/email-sent-from-RPi-Pico.png?resize=553%2C290&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"test email sent from Raspberry Pi Pico using MicroPython\" class=\"wp-image-150401\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/email-sent-from-RPi-Pico.png?w=553&amp;quality=100&amp;strip=all&amp;ssl=1 553w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/email-sent-from-RPi-Pico.png?resize=300%2C157&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 553px) 100vw, 553px\" \/><\/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 Raspberry Pi Pico W using MicroPython. Sending an email using an SMTP server is very simple 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 of how to send emails. Now you can use this in your projects to send notification alerts, sensor readings, and other applications.<\/p>\n\n\n\n<p>Learn more about the Raspberry Pi Pico with our eBook:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-micropython-ebook\/\" title=\"\">Learn Raspberry Pi Pico\/Pico W with MicroPython<\/a><\/li>\n<\/ul>\n\n\n\n<p>If you&#8217;re using an ESP32 or ESP8266, check the following tutorial: <a href=\"https:\/\/randomnerdtutorials.com\/micropython-send-emails-esp32-esp826\/\">MicroPython: Send Emails with the ESP32\/ESP826<\/a>.<\/p>\n\n\n\n<p>We hope you&#8217;ve found this tutorial useful. <\/p>\n\n\n\n<p>You can check all our <a href=\"https:\/\/randomnerdtutorials.com\/projects-raspberry-pi-pico\/\" title=\"\">Raspberry Pi Pico projects here<\/a>.<\/p>\n\n\n\n<p>Thanks for reading<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to send emails with the Raspberry Pi Pico using an SMTP server. This feature can be useful in your automation and IoT projects to send alert notifications, send &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Raspberry Pi Pico W: Sending Emails using SMTP Server (MicroPython)\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-send-email-micropython\/#more-150280\" aria-label=\"Read more about Raspberry Pi Pico W: Sending Emails using SMTP Server (MicroPython)\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":150406,"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":[324,326],"tags":[],"class_list":["post-150280","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-raspberry-pi-pico","category-raspberry-pi-pico-micropython"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Raspberry-Pi-Pico-Sending-Email-MicroPython.jpg?fit=1920%2C1080&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/150280","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=150280"}],"version-history":[{"count":10,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/150280\/revisions"}],"predecessor-version":[{"id":153366,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/150280\/revisions\/153366"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/150406"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=150280"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=150280"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=150280"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}