Trouble with LilyGO-T-SIM7000G and sending E-Mails

Hello! :blush:

I'm currently facing some challenges with my LilyGO T-SIM7000G module, and I'm hoping to get some assistance.

My ultimate objective is to utilize this module to send emails via LTE. In the future, I plan to have the module collect data from a sensor and send these data as CSV files via email. However, at the moment, I'm encountering difficulties with even sending a basic email. It seems there is a problem with the network connection because its not possible to log in. On the other hand it says that it is connected...

I would greatly appreciate any guidance or insights you can offer in order to make progress with my LilyGO T-SIM7000G module.

Thank you in advance for your help! :pray:

/* Sketch ist eine Mischung aus dem Sketch für die Testung der SIM7000G https://github.com/Xinyuan-LilyGO/LilyGO-T-SIM7000G/blob/master/examples/Arduino_TinyGSM/AllFunctions/AllFunctions.ino
und dem GSM Code Example der ESP_Mail_Client Libary https://github.com/mobizt/ESP-Mail-Client/commit/c6ce44ffcd86a94b812cea049716b109f8c0dbc0#diff-2fe767a3f54685ccde84ec2c14d6f12f6fb0cb93a03e8953dbfeb5d01f2dc72e */

#define TINY_GSM_MODEM_SIM7000
#include <TinyGsmClient.h>
#define TINY_GSM_RX_BUFFER 1024 // Set RX buffer to 1Kb
#define SerialAT Serial1


#define TINY_GSM_TEST_GPRS    true
#define TINY_GSM_USE_WIFI     false
#define TINY_GSM_POWERDOWN    true

// Setze GSM-PIN, falls vorhanden -->muss auch definert werden wenn kein PIN nötig ist
#define GSM_PIN ""

// Deine GPRS-Zugangsdaten der SIM Karte
const char apn[]  = "iot.1nce.net";     // APN
const char gprsUser[] = "";
const char gprsPass[] = "";

#include <ESP_Mail_Client.h>
#include <SPI.h>
#include <SD.h>
#include <Ticker.h>

#define uS_TO_S_FACTOR 1000000ULL  // Conversion factor for micro seconds to seconds
#define TIME_TO_SLEEP  60          // Time ESP32 will go to sleep (in seconds)

//Pinout für SIM Karte
#define UART_BAUD   115200
#define PIN_DTR     25
#define PIN_TX      27
#define PIN_RX      26
#define PWR_PIN     4

//Pinout für SD Karte
#define SD_MISO     2
#define SD_MOSI     15
#define SD_SCLK     14
#define SD_CS       13
#define LED_PIN     12

int counter, lastIndex, numberOfPieces = 24;
String pieces[24], input;

TinyGsm modem(SerialAT);

TinyGsmClient gsm_client(modem); // basic non-secure client



/* The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com*/
#define SMTP_HOST "****"
#define SMTP_PORT 465
/* The sign in credentials*/
#define AUTHOR_EMAIL "*******"
#define AUTHOR_PASSWORD "*****"
/* Recipient's email*/
#define RECIPIENT_EMAIL "*******"

SMTPSession smtp; //Erstellung Klasse und Objekt

// Callback-Funktion, um den Status des E-Mail-Versands zu überprüfen
void smtpCallback(SMTP_Status status);

// Wartezeit vor der Anmeldung am E-Mail-Server (in Millisekunden)
const unsigned long emailLoginDelay = 20000; // Zum Beispiel 10 Sekunden

void setup()
{
    // Baudrate
    Serial.begin(115200);
    delay(10);

 // Set LED OFF
    pinMode(LED_PIN, OUTPUT);
    digitalWrite(LED_PIN, HIGH);

    pinMode(PWR_PIN, OUTPUT);
    digitalWrite(PWR_PIN, HIGH);

    // Starting the machine requires at least 1 second of low level, and with a level conversion, the levels are opposite
    delay(1000);
    digitalWrite(PWR_PIN, LOW);

Serial.println("\nWait...");

    delay(1000);

    SerialAT.begin(UART_BAUD, SERIAL_8N1, PIN_RX, PIN_TX);

    // Restart takes quite some time
    // To skip it, call init() instead of restart()
    Serial.println("Initializing modem...");
    if (!modem.restart()) {
        Serial.println("Failed to restart modem, attempting to continue without restarting");
    }
}

void loop()
{

    // Restart takes quite some time
    // To skip it, call init() instead of restart()
    Serial.println("Initializing modem...");
    if (!modem.init()) {
        Serial.println("Failed to restart modem, attempting to continue without restarting");
    }

    String name = modem.getModemName();
    delay(500);
    Serial.println("Modem Name: " + name);

    String modemInfo = modem.getModemInfo();
    delay(500);
    Serial.println("Modem Info: " + modemInfo);


#if TINY_GSM_TEST_GPRS
    // Unlock your SIM card with a PIN if needed
    if ( GSM_PIN && modem.getSimStatus() != 3 ) {
        modem.simUnlock(GSM_PIN);
    }
#endif

    modem.sendAT("+CFUN=0");
    if (modem.waitResponse(10000L) != 1) {
        DBG(" +CFUN=0  false ");
    }
    delay(200);

    /*
      2 Automatic
      13 GSM only
      38 LTE only
      51 GSM and LTE only
    * * * */

    bool res = modem.setNetworkMode(2);
    if (!res) {
        DBG("setNetworkMode  false ");
        return ;
    }
    delay(200);

    /*
      1 CAT-M
      2 NB-Iot
      3 CAT-M and NB-IoT
    * * */
    res = modem.setPreferredMode(3);
    if (!res) {
        DBG("setPreferredMode  false ");
        return ;
    }
    delay(200);

    modem.sendAT("+CFUN=1");
    if (modem.waitResponse(10000L) != 1) {
        DBG(" +CFUN=1  false ");
    }
    delay(200);

  #if TINY_GSM_TEST_GPRS

    SerialAT.println("AT+CGDCONT?");
    delay(500);
    if (SerialAT.available()) {
        input = SerialAT.readString();
        for (int i = 0; i < input.length(); i++) {
            if (input.substring(i, i + 1) == "\n") {
                pieces[counter] = input.substring(lastIndex, i);
                lastIndex = i + 1;
                counter++;
            }
            if (i == input.length() - 1) {
                pieces[counter] = input.substring(lastIndex, i);
            }
        }
        // Reset for reuse
        input = "";
        counter = 0;
        lastIndex = 0;

        for ( int y = 0; y < numberOfPieces; y++) {
            for ( int x = 0; x < pieces[y].length(); x++) {
                char c = pieces[y][x];  //gets one byte from buffer
                if (c == ',') {
                    if (input.indexOf(": ") >= 0) {
                        String data = input.substring((input.indexOf(": ") + 1));
                        if ( data.toInt() > 0 && data.toInt() < 25) {
                            modem.sendAT("+CGDCONT=" + String(data.toInt()) + ",\"IP\",\"" + String(apn) + "\",\"0.0.0.0\",0,0,0,0");
                        }
                        input = "";
                        break;
                    }
                    // Reset for reuse
                    input = "";
                } else {
                    input += c;
                }
            }
        }
    } else {
        Serial.println("Failed to get PDP!");
    }


    Serial.println("\n\n\nWaiting for network...");
    if (!modem.waitForNetwork()) {
        delay(10000);
        return;
    }

    if (modem.isNetworkConnected()) {
        Serial.println("Network connected");
    }

    Serial.println("\n---Starting GPRS TEST---\n");
    Serial.println("Connecting to: " + String(apn));
    if (!modem.gprsConnect(apn, gprsUser, gprsPass)) {
        delay(10000);
        return;
    }

    if (modem.isNetworkConnected()) {
    Serial.println("Gerät ist mit dem Mobilfunknetzwerk verbunden.");
  } else {
    Serial.println("Gerät ist NICHT mit dem Mobilfunknetzwerk verbunden.");
    // Hier können Sie geeignete Maßnahmen ergreifen, wenn keine Netzwerkverbindung besteht.
  }

    Serial.print("GPRS status: ");
    if (modem.isGprsConnected()) {
        Serial.println("connected");
    } else {
        Serial.println("not connected");
    }

    String ccid = modem.getSimCCID();
    Serial.println("CCID: " + ccid);

    String imei = modem.getIMEI();
    Serial.println("IMEI: " + imei);

    String cop = modem.getOperator();
    Serial.println("Operator: " + cop);

    IPAddress local = modem.localIP();
    Serial.println("Local IP: " + String(local));

    int csq = modem.getSignalQuality();
    Serial.println("Signal quality: " + String(csq));

    SerialAT.println("AT+CPSI?");     //Get connection type and band
    delay(500);
    if (SerialAT.available()) {
        String r = SerialAT.readString();
        Serial.println(r);
    }

    Serial.println("\n---End of GPRS TEST---\n");
  #endif

if (modem.isNetworkConnected()) {
        Serial.println("Network connected");
    }


Session_Config config;

  config.server.host_name = SMTP_HOST;
  config.server.port = SMTP_PORT;
  config.login.email = AUTHOR_EMAIL;
  config.login.password = AUTHOR_PASSWORD;
  config.login.user_domain = F("127.0.0.1");

  // Declare the SMTP_Message class variable to handle to message being transport
  SMTP_Message message;

  // Set the message headers
  message.sender.name = F("ESP Mail");
  message.sender.email = AUTHOR_EMAIL;
  message.subject = F("Test sending plain text Email using GSM module");
  message.addRecipient(F("Someone"), RECIPIENT_EMAIL);

  // Set the message content
  message.text.content = "This is simple plain text message";
 
  // Set debug option
  smtp.debug(1);

  // Set the callback function to get the sending results
  smtp.callback(smtpCallback);

  smtp.setGSMClient(&gsm_client, &modem, GSM_PIN, apn, gprsUser, gprsPass);

  // Verzögerung vor der Anmeldung am E-Mail-Server
    delay(emailLoginDelay);

  // Versuchen Sie, sich am E-Mail-Server anzumelden und E-Mails zu senden
  smtp.connect(&config);

  // Start sending Email and close the session
  if (!MailClient.sendMail(&smtp, &message))
    Serial.println("Error sending Email, " + smtp.errorReason());
}


void smtpCallback(SMTP_Status status)
{
 
  Serial.println(status.info());

  if (status.success())
  {
    // See example for how to get the sending result
  }
  
}

This is always the response I get.

16:29:53.960 -> Initializing modem...
16:29:54.480 -> Modem Name: SIMCOM SIM7000G
16:29:54.967 -> Modem Info: SIM7000G R1529
16:30:01.185 ->
16:30:01.185 ->
16:30:01.185 ->
16:30:01.185 -> Waiting for network...
16:30:02.217 -> Network connected
16:30:02.217 ->
16:30:02.217 -> ---Starting GPRS TEST---
16:30:02.217 ->
16:30:02.217 -> Connecting to: iot.1nce.net
16:30:04.295 -> Gerät ist mit dem Mobilfunknetzwerk verbunden.
16:30:04.295 -> GPRS status: connected
16:30:04.295 -> CCID: 89882280666038388991
16:30:04.295 -> IMEI: 869951035874639
16:30:04.295 -> Operator: Telekom.de 1nce.net
16:30:04.295 -> Local IP: 29671690
16:30:04.295 -> Signal quality: 25
16:30:05.807 ->
16:30:05.807 -> +CPSI: GSM,Online,262-01,0x972d,25554,124 EGSM 900,-61,0,46-46
16:30:05.807 ->
16:30:05.807 -> OK
16:30:05.807 ->
16:30:05.807 ->
16:30:05.807 -> ---End of GPRS TEST---
16:30:05.807 ->
16:30:05.808 -> Network connected
16:30:25.821 -> #### Error, connection closed
16:30:25.821 -> ! E: connection closed
16:30:25.821 ->
16:30:25.821 -> #### Error, not yet log in
16:30:25.821 -> ! E: not yet log in
16:30:25.821 -> Error sending Email, not yet log in

i'm using LilyGo-T-SIM7000G but instead of SMTPSession i implemented AT commands, based on
SIM7000_Email_Application_Note.pdf
And i can confirm sending emails by LilyGo-T-SIM7000G working.

Was facing the same issue. Filed Broken TinyGSM detection logic · Issue #343 · mobizt/ESP-Mail-Client · GitHub in the ESP-Mail-Client repository. They seem to have a bug. I had to manually modify the code in their library to get past the connection closed error.

You are using library incorrectly.

IMPORTANT
The GSM module macros e.g. TINY_GSM_MODEM_SIM7600 should be defined in two locations.

  1. In src/ESP_Mail_FS.h or in your own defined config at src/Custom_ESP_Mail_FS.h or adding TINY_GSM_MODEM_SIM7600 in compiler build flags.
  2. In your sketch.

Turns out we were using the library incorrectly. Since the author of the library deleted the issue, I'll describe the issue here for future people visiting this page. If you carefully read the README.md file, it instructs you to create a Custom_ESP_Mail_FS.h file in the library directory and define your modem type there (e.g., #define TINY_GSM_MODEM_SIM7600). However, beware that not all modem types are listed in their extras/Networks.h file (ESP-Mail-Client/src/extras/Networks.h at 78b8e7b4270199dab5f14265ad565acd80f10465 · mobizt/ESP-Mail-Client · GitHub). If your modem type is not listed, you have to manually edit that file to add it.

Your post quite off topic. Your issue is different from the owner original post.

Actually, he should ask this specific question on the library Github instead and it should be ok if he reads the comment in the example to setup unless he will get the same issue if he just edits the example without reading the document and example comment to set it up correctly.

I delete your issue on the library Github repository because of your misunderstanding that can cause confusion to others.

There is no TINY_GSM_MODEM_A7670 defined in TinyGSM library as you are asking for and modifying the ESP Email Client library source code is not necessary as it supports all GSM modules that supported by latest version of TinyGSM library.

In your case TINY_GSM_MODEM_SIM7600 macro should be defined, and it is compatible with all SIMA7xxx GSM modules which you can see the statement in the example comment.

The comment on the top of examples described the hardware used in the example i.e. ESP32 and SIMCom SIMA7670.