Send email with esp8266 and Arduino (Library v1.x)

Spread the love

I finally upgrade this library with support for Arduino (Ethernet, UIPEthernet and SD as storage), esp32 (SD and SPIFFS) and esp8266 (SD and SPIFFS), with the possibility of attaching files.
Refer to this article for the version 2.x of the library “Send email with attachments (v2.x library)“.

A simple method to notify a problem is to use email, It’s very usefully and simple to share, so I created a library to do It. I get some code from GSender a library that It’s quite simple, but not so complete and configurable.

Esp8266 and Arduino EMailSender library

This library use the SMTP:

The Simple Mail Transfer Protocol (SMTP) is a communication protocol for electronic mail transmission. As an Internet standard, SMTP was first defined in 1982 by RFC 821, and updated in 2008 by RFC 5321 to Extended SMTP additions, which is the protocol variety in widespread use today. Mail servers and other message transfer agents use SMTP to send and receive mail messages. Proprietary systems such as Microsoft Exchange and IBM Notes and webmail systems such as Outlook.com, Gmail and Yahoo! Mail may use non-standard protocols internally, but all use SMTP when sending to or receiving email from outside their own systems. SMTP servers commonly use the Transmission Control Protocol on port number 25. (cit WiKi)

For the examples I use a gmail dedicated account, I create a new one account because you must reduce security to use It with an external program.

Backward compatibility

From esp8266 core 2.4.2 and next version upper and equal than 2.5.2 something are changed and to support old versione 2.4.2 I add a define to allow you to work and that core.

So if you have a esp8266 core 2.4.2 or less you must decomment this line

// Uncomment if you use esp8266 core <= 2.4.2
#define ARDUINO_ESP8266_RELEASE_2_4_2

Library

You can find my library here.

To download.

Click the DOWNLOADS button in the top right corner, rename the uncompressed folder EMailSender.

Check that the EMailSender folder contains EMailSender.cpp and EMailSender.h.

Place the EMailSender library folder your /libraries/ folder.

You may need to create the libraries subfolder if its your first library.

Restart the IDE.

Usage

Constructor: Default value is quite simple and use GMail as smtp server.

EMailSender emailSend("smtp.account@gmail.com", "password");

If you want use onother provider you can use more complex (but simple) contructor

EMailSender(const char* email_login, const char* email_password, bool isSecure = false);

EMailSender(const char* email_login, const char* email_password, const char* email_from, bool isSecure = false);

EMailSender(const char* email_login, const char* email_password, const char* email_from, const char* smtp_server, uint16_t smtp_port, bool isSecure = false);
  • email_login: login to account smtp
  • email_password: password account smtp
  • email_from: email of sender
  • smtp_server: server SMTP
  • smtp_port: SMTP port
  • isSecure = false: if false BearSSL allows for ‘insecure’ TLS connections

You must connect to WIFI :P.

Create a message with the structure EMailMessage

    EMailSender::EMailMessage message;
    message.subject = "Subject";
    message.message = "Hi, How are you<br>Fine.";

Send message:

    EMailSender::Response resp = emailSend.send("account_to_send@gmail.com", message);

Then check the response:

    Serial.println("Sending status: ");
    Serial.println(resp.code);
    Serial.println(resp.desc);
    Serial.println(resp.status);

Example output:

Connection: ESTABLISHED
Got IP address: 192.168.1.104
Sending status: 
1
0
Message sent!

GMail enable

Allow less secure apps to access your Gmail account

Google may block sign-in attempts from some apps or devices that do not use modern security standards. Since these apps and devices are easier to break into, blocking them helps keep your account safe.

To disable this security feature:

  1. Sign in to Gmail
  2. Click here to access Less Secure App Access in My Account.
  3. Next to “Allow less secure apps: OFF,” select the toggle switch to turn ON.

This setting may not be available for:

For G-Suite users: Enabling less secure apps to access accounts

  1. Sign in to your Google Admin console (Sign in using an administrator account, not your current account.
  2. Click Security > Basic settings.
  3. Under Less secure apps, select Go to settings for less secure apps.
  4. In the subwindow, select the Allow users to manage their access to less secure apps radio button.

Once you’ve set Allow users to manage their access to less secure apps to on, affected users within the selected group or Organizational Unit will be able to toggle access for less secure apps on or off themselves.

G-Suite admins: Enforcing access to less secure apps for all users

Use this setting when you want to ensure that access by a less secure app is available to all for a limited time, such as for upgrades.

  1. Sign in to your Google Admin console.Sign in using an administrator account
  2. Click Security > Basic settings.
  3. Under Less secure apps, select Go to settings for less secure apps.
  4. In the subwindow, select the Enforce access to less secure apps for all users radio button.

Once you’ve set Enforce access to less secure apps for all users to on, affected users within the selected group or Organizational Unit will not be able to toggle access for less secure apps off themselves. You will have to set the setting back to Allow users to manage their access to less secure apps to allow them to toggle access for less secure apps on or off themselves.

Thanks

GitHub library


Spread the love

63 Responses

  1. Bulchai Nirattisai says:

    Thank you very much.
    This is so simple and very useful for tons of IoT projects.

  2. Alexandru Goman says:

    Hello sir, let me just start by saying thank you and how amazing this project is, but i have a problem. I can’t compile the code, it gives me this error.

    Arduino: 1.8.10 (Mac OS X), Board: “Arduino/Genuino Uno”

    Multiple libraries were found for "EMailSender.h"
    Used: /Users/alex/Documents/Arduino/libraries/EMailSender-master
    In file included from /Users/alex/Documents/Arduino/libraries/EMailSender-master/examples/EMailSenderTest/EMailSenderTest.ino:2:0:
    /Users/alex/Documents/Arduino/libraries/EMailSender-master/EMailSender.h:10:10: fatal error: WiFiClientSecure.h: No such file or directory
    #include
    ^~~~~~~~~~~~~~~~~~~~
    compilation terminated.
    exit status 1
    Error compiling for board Arduino/Genuino Uno.

    What do you think the cause may be? And what solution do you think there is. Thank you.

    • Hi Alexandru,
      It’s seems in the time I lost Arduino compatibility, sorry, when I have some time I try to restore with ethernet.
      Bye Renzo

    • MJ Ferreiro says:

      Looks like you’re trying to upload to an Arduino Uno. The Uno has no wifi. Change the board to an ESP8266.

      • Hi Ferreiro, It’s true I lost compatibility, but when I find some time I restore the support for Ethernet.
        Bye Renzo

      • Hi Ferreiro,
        now I restored support for Arduino (UIPEthernet and Ethernet but this not support SSL and TLS) esp8266 and esp32.
        I add support for attachments and other features.
        It’s in beta release, but I check a lot of situation and seems It’s work good.
        You can find a beta release in this branch
        GitHub repo

        I add a full documentation soon, now you can refer the examples.

        I hope you try this version.
        Bye Renzo

    • Hi Alexandru,
      now I restored support for Arduino (UIPEthernet and Ethernet) esp8266 and esp32.
      I add support for attachments and other features.
      It’s in beta release, but I check a lot of situation and seems It’s work good.
      You can find a beta release in this branch
      GitHub repo

      I hope you try this versione.
      Bye Renzo

  3. alan says:

    This is great, thanks for sharing
    I would also like to use it with an esp32 but it does not compile, would it be possible/easy to convert?

    • Hi Alan,
      I try with an esp32 and It’s work correctly.
      But I check that in VSCode and Eclipse there is a bug in the plugin that give an error on compiling time.
      Try with ArduinoIDE and post your error.
      Thanks Renzo

  4. peter says:

    I’m still trying to make this work!! Do I need to edit the .cpp and .h files?

    I Keep getting this error below? Can you help at all??

    Arduino: 1.8.9 (Mac OS X), Board: “LOLIN(WEMOS) D1 R2 & mini, 80 MHz, Flash, 4M (1M SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch, 921600”

    /Users/wilmsworld/Documents/Arduino/libraries/EMailSender-master2/EMailSender.cpp: In member function 'EMailSender::Response EMailSender::send(const char*, EMailSender::EMailMessage&)':
    /Users/wilmsworld/Documents/Arduino/libraries/EMailSender-master2/EMailSender.cpp:169:10: error: base operand of '->' has non-pointer type 'axTLS::WiFiClientSecure'
    client->setInsecure();
    ^
    /Users/wilmsworld/Documents/Arduino/libraries/EMailSender-master2/EMailSender.cpp:170:22: error: base operand of '->' has non-pointer type 'axTLS::WiFiClientSecure'
    bool mfln = client->probeMaxFragmentLength(host.c_str(), port, 512);
    ^
    /Users/wilmsworld/Documents/Arduino/libraries/EMailSender-master2/EMailSender.cpp:170:47: error: 'host' was not declared in this scope
    bool mfln = client->probeMaxFragmentLength(host.c_str(), port, 512);
    ^
    /Users/wilmsworld/Documents/Arduino/libraries/EMailSender-master2/EMailSender.cpp:170:61: error: 'port' was not declared in this scope
    bool mfln = client->probeMaxFragmentLength(host.c_str(), port, 512);
    ^
    /Users/wilmsworld/Documents/Arduino/libraries/EMailSender-master2/EMailSender.cpp:175:11: error: base operand of '->' has non-pointer type 'axTLS::WiFiClientSecure'
    client->setBufferSizes(512, 512);
    ^
    exit status 1
    Error compiling for board LOLIN(WEMOS) D1 R2 & mini.

    This report would have more information with
    “Show verbose output during compilation”
    option enabled in File -> Preferences.

    • Hi,
      you probably have a 2.4.2 esp8266 core, you must decomment
      //#define ARDUINO_ESP8266_RELEASE_2_4_2
      And tell me if you resolve your issue.

      Bye Renzo

      • peter says:

        Ok so I decommented in the .h file, but I still have errors:-

        /Users/wilmsworld/Documents/ Arduino/libraries/EMailSender-master2/EMailSender.cpp: In member function 'EMailSender::Response EMailSender::send(const char*, EMailSender::EMailMessage&)':
        EMailSender.cpp:169:10: error: base operand of '->' has non-pointer type 'axTLS::WiFiClientSecure'
        client->setInsecure();
        ^
        EMailSender.cpp:170:22: error: base operand of '->' has non-pointer type 'axTLS::WiFiClientSecure'
        bool mfln = client->probeMaxFragmentLength(host.c_str(), port, 512);
        ^
        EMailSender.cpp:170:47: error: 'host' was not declared in this scope
        bool mfln = client->probeMaxFragmentLength(host.c_str(), port, 512);
        ^
        EMailSender.cpp:170:61: error: 'port' was not declared in this scope
        bool mfln = client->probeMaxFragmentLength(host.c_str(), port, 512);
        ^
        EMailSender.cpp:175:11: error: base operand of '->' has non-pointer type 'axTLS::WiFiClientSecure'
        client->setBufferSizes(512, 512);
        ^
        exit status 1
        base operand of '->' has non-pointer type 'axTLS::WiFiClientSecure'

        any ideas??

        • Azz
          I check the Iesterday commit and I see that there is an error, and I commit an updated version now.
          But if you decomment the define that part of code is skipped

          #ifndef ARDUINO_ESP8266_RELEASE_2_4_2
          if (this->isSecure == false){
          client.setInsecure();
          bool mfln = client.probeMaxFragmentLength(this->smtp_server, this->smtp_port, 512);

          DEBUG_PRINTLN(“MFLN supported: %s\n”, mfln ? “yes” : “no”);

          if (mfln) {
          client.setBufferSizes(512, 512);
          }
          }
          #endif

          Try to download last version, decomment define
          #define ARDUINO_ESP8266_RELEASE_2_4_2

          and rebuild with pay attention if the EmailSender library is updated.

          Please send me the result, Thanks Renzo

          • peter says:

            Thats great it works perfectly now! Many thanks for your work and your fast replies to my questions!!

  5. benate100 says:

    Bonjour, Monsieur,
    c’était pour voir s’il y avait un moyen d’envoyer des variables de notre programme ainsi que du texte en html.

    • benate100 says:

      EN :
      Good morning, sir,
      was to see if there was a way to send variables from our program as well as html text.

      • Hi benate100,
        what do you mean with “send variables from our program”?
        However I don’t apply escae caracter to the text so if you send html tag It’s work correctly.
        Bye Renzo

  6. benate100 says:

    Hello again, I come back to you because when I want to send a mail, I get the error “Could not connect to mail server”. Do you have an idea where this can come from?

    my settup:
    uint16_t smtp_port = 465;
    char* smtp_server = strdup(“smtp.gmail.com”);

  7. Christine Thompson says:

    Hi, great and easy to use software, however can it be used to attach files to the email?

    • gestione says:

      Hi Christine,
      no It isn’t possible now.
      I have in mind (as you can see in github issue) 2 enhancement, fisrt the possibility to select mime/type the other the possibility to attach a file, but now I spent my time on a new project (Remote refuel tank).
      Bye Renzo

    • Hi Christine,
      now I restored support for Arduino (UIPEthernet and Ethernet but this not support SSL and TLS) esp8266 and esp32.
      I add support for attachments and other features.
      It’s in beta release, but I check a lot of situation and seems It’s work good.
      You can find a beta release in this branch
      GitHub repo

      I add a full documentation soon, now you can refer the examples.

      I hope you try this version.
      Bye Renzo

  8. MJ Ferreiro says:

    Buona giornata Renzo,

    Dude… I just want to say thanks for posting this code. It works flawlessly.
    (I have tried a couple of sketches like this in the past like “AlertMe” etc… but I didn’t know how to update the JSON code from ver 5 to 6 so the sketch wouldn’t compile.)
    I’ve got a million ideas that I can finally apply this to. You made my day bro!!!

  9. Devin says:

    I keep getting an error when trying to send a message using gmail. I did enable less secure apps already. Got this both when trying to set it up myself from your code above and also from a full example code. Anyone know the cause or solution?

    Sending status:
    235
    SMTP AUTH error
    0

    • It’s possible that you have write a wrong password, or you have decommented the core 2.4.2 with new version.
      Bye Renzo

    • Gianpaolo P says:

      I was getting the same error then I changed this line in the code:

      EMailSender emailSend(“smtp.account@gmail.com”, “password”);

      First time I wrote “smtp.mypersonalmail@gmail.com” then I tried “mypernoalemail@gmail.com” without the “smtp.” and it worked for me.

  10. Joergen says:

    Hello,

    dou you plan to include LittleFS Support?

    • Hi Joergen,
      I surely support LittleFS, I tested It, but I’d like to find the better solution to activate It.
      Probably become a define to switch from SPIFFS to LittleFS, but for esp32 also I need to permit the select of FAT.
      Bye Renzo

      • Joergen says:

        Thank you Renzo,

        I am now testing but get this Error at compile Time:
        EMailSender.h:270:90: error: could not convert ‘{0, ()}’ from ” to ‘EMailSender::Attachments’.

        Did I miss something?
        Thanks for fiving me a Hint!

        • I think you must download the last version.
          Tell me if fix.
          Bye Renzo

          • Joergen says:

            You were right.
            The Problem was related to the old Version.
            I got another Problem. There was a Conflict between Arduino and ESP8266 SdFat Libraries. Solved!
            Now I face another Problem. I was already succesfully using your standard Library to send Alert Emails.
            I now use the new Library for the Attachment Features.
            I get the SMTP Error 354 for both your “EMailSenderEsp8266GMailSPIFFSAttachTest” Example and for my previously working Sketch.

            Do you have any Hint?
            Cheers

            • Yes, If you have installed some SdFat library esp8266 not work, esp8266 have SdFat inside core in the version > 2.4.2.
              Mmm.. It’s strange, I try now and with my WeMos D1 and GMail provider work correctly, please send me some additional information like core file sended etc..
              Bye Renzo

          • Joergen says:

            Hello Renzo,

            My installed Esp8266 core Version is 2.7.1.
            I used the “EMailSenderEsp8266GMailSPIFFSAttachTest.ino” Example.EMailSender with original data Folder Content.
            I only adjusted the EMailSender Declaration with:
            EMailSender emailSend(“xxxxxxx@sunrise.ch”, “xxxxxxx”, “xxxxxxx@sunrise.ch”, “smtp2.sunrise.ch”, 465);

            Serial Output gives:
            Connecting to xxxxxxx
            ……………………………..
            Connection: ESTABLISHED
            Got IP address: xxx.xxx.xxx.xxx
            Sending status:
            0
            354
            SMTP DATA error

            My Problem may be related to the Fact that I am not using gmail but a different Provider.
            I cannot use gmail as I need 2-Step Verification in my gmail Account.

            Cheers
            Joergen

            • Hi Joergen,
              It’s strange, I change only the write method, but I’m going to debug with other provider with the same characteristic.

              For GMail I’ve the two step verification too, but GMail allow to create multiple account connected to the master account, for my usageI create smtp.mischianti@gmail.com account with less secure functions.

              Bye Renzo

  11. Joergen says:

    Hello Renzo,

    I confirm, it works with a gmail Account. Great!

    I noticed that it took ~2mins to send the Attachment of the Example App. Is the same for you?
    Still to find why it does not work with a non-gmail Account.
    And … I would be really happy with LittleFS (if I don’t abuse…).

    Cheers
    Joergen

    • The problem of latency is generated by encode on base64 if you disable It (like for text file with no special character) become fast.
      If you doesn’t encode image sometime the image arrive with some artefact.

      But this evening I’m going to release the updated article with all features of version 2 of the library, where I expain better also this problem.

      I already do a tutorial on how to use LittleFS and I’d like to release that article with tutorial of LittleFS and than upgrade EMailSender

      Bye Renzo

    • Hi Joergen,
      I try yahoo email, but I can send email without problem, i try also to create an email with you provider but i can’t, you know an email provider with the same problem that i can use for my testing?
      Can you uncomment the debug define and send me the log.
      Bye Renzo

  12. Joergen says:

    Hello Renzo,

    I have an output File I can send you. May I send it to: newsletter@mischianti.org ?
    Everything is fine until the Recipient Section, Here is the End of the Output File where the Problem arises:

    RCPT TO:
    501 5.5.2 : Helo command rejected: Invalid name

    DATA:
    554 5.5.1 Error: no valid recipients

    Sending status:
    0
    354
    SMTP DATA error

    You see Errors 501 and 554 after Recipient Declaration. I tried with different Recipients with same Results.

    Cheers
    Joergen

  13. John says:

    I want to THANK YOU for such an elegant solution to what seems an enormous problem! Once Gmail went to required encryption and heightened security, all of the old YouTubes and Tutorials no longer work. Some claim to fix it, but they don’t. I must have spent days trying to get Gmail to work on my Arduino devices.

    I have only used your library to send texts through Gmail so far, yours work perfectly!

  14. Morne' Stander says:

    Hi Renzo

    I love the simplicity of your code which helps alot.
    I am however stuck.

    I am using the following line with parameters:
    EMailSender emailSend(“xxxxxxxxx@outlook.com”, “password”, “xxxxxxxxx@outlook.com”, “smtp-mail.outlook.com”, 587);

    Monitoring my Serial Port I get:

    Connecting to [WiFiEsp] Connected to MS_DK_FB [2Ghz]
    MS_DK_FB [2Ghz]

    Connection: ESTABLISHED
    Got IP address: 192.168.101.120
    Sending status:
    0
    2
    Could not connect to mail server

    Connection: ESTABLISHED
    Got IP address: 192.168.101.120
    Sending status:
    0
    2

    I would really appreciate your assistance.

    Regards
    M

    • Hi Morne,
      sorry but port 587 means that It works with TLS, and now that security protocol isn’t supported.
      I work to support It, but I’d like to use define to permit the deactivation/activation because TLS needs many resources, and the library has begun too weigh.
      If there is news, I update the articles.
      Bye Renzo

      • Morne' Stander says:

        Hi Lorenzo.
        Thank you for the quick response.

        I ended up setting up a different gmail account and switched on the non-secure log-in function within gmail.
        I changed the code to: EMailSender emailSend(“xxxxxx@gmail.com”, “password”); and I’m 100% sure the credentials are correct.

        I still however get:
        Connecting to [WiFiEsp] Connected to MS_DK_FB [2Ghz]
        MS_DK_FB [2Ghz]

        Connection: ESTABLISHED
        Got IP address: 192.168.101.181
        Sending status:
        0
        2
        Could not connect to mail server

        Perhaps I should mention that I’m using the Arduino Mega connected to the ESP8266 over serial.
        I also send data to a remote server via the ESP8266 and all that functions well.
        Any assistance would be appreciated.

  15. Emilio says:

    Hi Renzo,
    I tryed to use this library with the EMailSenderTest example but I get this after taking a long time to connect:

    Connection: ESTABLISHED
    Got IP address: 169.254.137.246
    Sending status:
    0
    2
    Could not connect to mail server

    I’m using ESP8266 Core 3.0.2 and I’ve created a gmail account for this tests and activated the less secure apps option as shown above but it still can’t connect to mail server, am I missing something?
    I notice that the IP obtained is different that my laptop’s IP first 3 numbers, which should start with 192.168.0, with other sketches I get IPs starting with 192.168.0 but with this example I don’t.

    Any idea?

    Thanks in advance,
    Best regards.

    • Hi Emilio,
      The error says that you can’t contact the SMTP server. Probably a network problem. Try to do a telnet to the SMTP server and port.
      Bye Renzo

      • Emilio says:

        Hi again Renzo and thanks for the answer,

        I tried the telnet advice from cmd with the command “telnet smtp.gmail.com 587” with this response “220 smtp.gmail.com ESMTP z188sm7347348ooa.8 – gsmtp” which honestly I don’t understand and with the command “telnet smtp.gmail.com 465” with a black screen response, is this helpful?

        By the other hand I’ve found something about my issue: my ESP82266 module doesn’t connect quickly to my access point (I’m 2 meters away) it takes up to 3-5 minutes and sometimes it doesn’t connect at all but when it does it shows the same error that before (Could not connect to mail server) or a new one saying that it has been a TIMEOUT.
        I tried connecting to a range extender which is even further away (about 6 meters) and it connects in 30 seconds or less and works flawlessly sending 10/10 emails with no problem at all, do yo have any idea of what’s going on?

        Thanks again,
        Best regards.

  16. Jules says:

    Hello, I have this error :
    In file included from C:\Users\Jules\OneDrive\Documents\Arduino\Test_ mail\sketch_mar6a\sketch_mar6a.ino:19:0:
    C:\Users\Jules\OneDrive\Documents\Arduino\libraries\EMailSender/EMailSender.h:329:12: fatal error: SD.h: No such file or directory
    #include
    compilation terminated.exit status 1
    Compilation error: exit status 1

    I think I must be missing a library, but I don’t know which one. This error occurred after an update of the arduino IDE.
    Could you help me?
    Thanks

    • Hi Jules,
      I think you need to add the SD library.
      Bye Renzo

      • Jules says:

        ok thanks, it works.
        for the “account” and “password” parts, you have to code them in 64 or you can leave them in plain text.
        I’m testing the code with SendGrid but I’m getting an error connecting to the mail server.

  17. Jules says:

    Renzo, you should modify the explanations for sending mail via SendGrid on this line:
    EMailSender emailSend(“apikey”, “your_password_apikey”, “your_mail”, “smtp.sendgrid.net”, 587 );
    – apikey signals that we’re going to send a code related to an api module
    – your_password_apikey is the password given by Sendgrid when requesting an SMTP Relay key.
    – your_mail is the Sendgrid login address.
    – You must use 587 as port
    and thanks for your forum.
    Question: can I use an arduino to change the name of a file on a remote ftp (personally, I use WebHost)?

  18. Facundo says:

    Hi Renzo,
    First of all, thank you very much for your contribution, it was really helpful.

    I just want to let you know about a future change of Google Security, that will cause errors with this library:

    “Less secure apps & your Google Account:
    Starting on September 30, 2024, less secure apps, third-party apps, or devices that have you sign in with only your username and password will no longer be supported for Google Workspace accounts. For exact dates, visit Google Workspace Updates. To continue to use a specific app with your Google Account, you’ll need to use a more secure type of access that doesn’t share password data. Learn how to use Sign in with Google.”

    You can check the information in this link https://support.google.com/accounts/answer/6010255?hl=en&sjid=9237137473395267088-SA

    Thanks again,
    Best regards.

Leave a Reply

Your email address will not be published. Required fields are marked *