Probleme d'envoi de mail avec la carte uno r4 wifi

Bonjour a tous

Je me lance dans l’utilisation d’arduino

Je suis un nouvel utilisateur arduino et je rencontre un problème.

Je voudrais que mes données de température me soient envoyés par mail en cas de dépassement .

Seulement j’ai une carte uno r4 wifi et j’utilise du code pour esp8266. Mon problème est que j’arrive a me connecter au wifi et ensuite plus rien alors que je voudrais recevoir un mail. J’ai cherché une solution mais en vain .

J’utilise du code récupéré sur un site.

Ma question : Est que l’écriture est correct , quelles sont les modifications a faire. J’ai vu qu’il était préférable d’utiliser un carte wifi séparée. Est-ce exact

Je vous remercie a l’avance

Serge

 Rui Santos
  Complete project details at:
   - ESP32: https://RandomNerdTutorials.com/esp32-send-email-smtp-server-arduino-ide/
   - ESP8266: https://RandomNerdTutorials.com/esp8266-nodemcu-send-email-smtp-server-arduino/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  Example adapted from: https://github.com/mobizt/ESP-Mail-Client
*/

#include <Arduino.h>
#if defined(ESP32)
  #include <WiFi.h>
#elif defined(ESP8266)
  #include <ESP8266WiFi.h>
#endif
#include <ESP_Mail_Client.h>

#define WIFI_SSID "Freebox"
#define WIFI_PASSWORD "xxmbxxxxxxxxbqdktdd"

/** 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 "smtp.free.fr"
#define SMTP_PORT 465

/* The sign in credentials */
#define AUTHOR_EMAIL "Arduino_carte"
#define AUTHOR_PASSWORD "iree yddk ihzl xkcx "

/* Recipient's email*/
#define RECIPIENT_EMAIL "xxx@laposte.net"

/* Declare the global used SMTPSession object for SMTP transport */
SMTPSession smtp;

/* Callback function to get the Email sending status */
void smtpCallback(SMTP_Status status);

void setup(){
  Serial.begin(115200);
  Serial.println();
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();

  /*  Set the network reconnection option */
  MailClient.networkReconnect(true);

  /** Enable the debug via Serial port
   * 0 for no debugging
   * 1 for basic level debugging
   *
   * Debug port can be changed via ESP_MAIL_DEFAULT_DEBUG_PORT in ESP_Mail_FS.h
   */
  smtp.debug(1);

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

  /* Declare the Session_Config for user defined session credentials */
  Session_Config config;

  /* Set the session 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 = "";

  /*
  Set the NTP config time
  For times east of the Prime Meridian use 0-12
  For times west of the Prime Meridian add 12 to the offset.
  Ex. American/Denver GMT would be -6. 6 + 12 = 18
  See https://en.wikipedia.org/wiki/Time_zone for a list of the GMT/UTC timezone offsets
  */
  config.time.ntp_server = F("pool.ntp.org,time.nist.gov");
  config.time.gmt_offset = 3;
  config.time.day_light_offset = 0;

  /* Declare the message class */
  SMTP_Message message;

  /* Set the message headers */
  message.sender.name = F("ESP");
  message.sender.email = AUTHOR_EMAIL;
  message.subject = F("ESP Test Email");
  message.addRecipient(F("Sara"), RECIPIENT_EMAIL);
    
  /*Send HTML message*/
  /*String htmlMsg = "<div style=\"color:#2f4468;\"><h1>Hello World!</h1><p>- Sent from ESP board</p></div>";
  message.html.content = htmlMsg.c_str();
  message.html.content = htmlMsg.c_str();
  message.text.charSet = "us-ascii";
  message.html.transfer_encoding = Content_Transfer_Encoding::enc_7bit;*/

   
  //Send raw text message
  String textMsg = "Hello World! - Sent from ESP board";
  message.text.content = textMsg.c_str();
  message.text.charSet = "us-ascii";
  message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
  
  message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
  message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay;


  /* Connect to the server */
  if (!smtp.connect(&config)){
    ESP_MAIL_PRINTF("Connection error, Status Code: %d, Error Code: %d, Reason: %s", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str());
    return;
  }

  if (!smtp.isLoggedIn()){
    Serial.println("\nNot yet logged in.");
  }
  else{
    if (smtp.isAuthenticated())
      Serial.println("\nSuccessfully logged in.");
    else
      Serial.println("\nConnected with no Auth.");
  }

  /* Start sending Email and close the session */
  if (!MailClient.sendMail(&smtp, &message))
    ESP_MAIL_PRINTF("Error, Status Code: %d, Error Code: %d, Reason: %s", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str());

}

void loop(){
}

/* Callback function to get the Email sending status */
void smtpCallback(SMTP_Status status){
  /* Print the current status */
  Serial.println(status.info());

  /* Print the sending result */
  if (status.success()){
    // ESP_MAIL_PRINTF used in the examples is for format printing via debug Serial port
    // that works for all supported Arduino platform SDKs e.g. AVR, SAMD, ESP32 and ESP8266.
    // In ESP8266 and ESP32, you can use Serial.printf directly.

    Serial.println("----------------");
    ESP_MAIL_PRINTF("Message sent success: %d\n", status.completedCount());
    ESP_MAIL_PRINTF("Message sent failed: %d\n", status.failedCount());
    Serial.println("----------------\n");

    for (size_t i = 0; i < smtp.sendingResult.size(); i++)
    {
      /* Get the result item */
      SMTP_Result result = smtp.sendingResult.getItem(i);

      // In case, ESP32, ESP8266 and SAMD device, the timestamp get from result.timestamp should be valid if
      // your device time was synched with NTP server.
      // Other devices may show invalid timestamp as the device time was not set i.e. it will show Jan 1, 1970.
      // You can call smtp.setSystemTime(xxx) to set device time manually. Where xxx is timestamp (seconds since Jan 1, 1970)
      
      ESP_MAIL_PRINTF("Message No: %d\n", i + 1);
      ESP_MAIL_PRINTF("Status: %s\n", result.completed ? "success" : "failed");
      ESP_MAIL_PRINTF("Date/Time: %s\n", MailClient.Time.getDateTimeString(result.timestamp, "%B %d, %Y %H:%M:%S").c_str());
      ESP_MAIL_PRINTF("Recipient: %s\n", result.recipients.c_str());
      ESP_MAIL_PRINTF("Subject: %s\n", result.subject.c_str());
    }
    Serial.println("----------------\n");

    // You need to clear sending result as the memory usage will grow up.
    smtp.sendingResult.clear();
  }
}

`

regardez

Bonjour J-M-L jackson
je te remercie de ta reponse. J'ai instaallé le code mais je rencontre un probleme que je ne comprend pas. Je lance le croquis ca fonctionne bien jusqu'a la ligne de l'auteur de l'envoie et la j'ai in message qui me dit que ca n'est pas bon. J'ai essayer d'autre compte maiss sans resultat. Si je peux avoir une aide la dessus ce serait sympatique. je joins le code et la copie du resultat.
Merci d'avance serge

08:45:03.006 -> > C: perform SSL/TLS handshake

08:45:04.795 ->

08:45:04.795 -> #### Sending greeting response...

08:45:04.795 -> > C: send SMTP command, EHLO

08:45:06.116 -> < S: 250-smtp.gmail.com at your service, [82.66.252.120]

08:45:06.532 -> < S: 250-SIZE 35882577

08:45:06.856 -> < S: 250-8BITMIME

08:45:08.252 -> < S: 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH

08:46:21.340 -> < S: 250-ENHANCEDSTATUSCODES

08:46:21.716 -> < S: 250-PIPELINING

08:46:22.026 -> < S: 250-CHUNKING

08:46:22.298 -> < S: 250 SMTPUTF8

08:46:22.462 ->

08:46:22.462 -> #### Logging in...

08:46:22.462 -> > C: send SMTP command, AUTH PLAIN

08:46:22.462 -> > C: Mon_Arduino

08:46:22.462 -> > C: ****************

08:46:24.253 -> < S: 535-5.7.8 Username and Password not accepted. For more information, go to

08:46:26.805 -> < S: 535 5.7.8 Can't sign in to your Google Account - Gmail Help m15-20020adffe4f000000b0033ed7181fd1sm1210114wrs.62 - gsmtp

08:46:26.912 -> #### Error, authentication failed

08:46:26.912 -> ! E: authentication failed

08:46:27.018 -> Connection error, Status Code: 535, Error Code: -105, Reason: authentication failed

// Arduino Uno R4 Wi-Fi Temperature Sensor with Text and Email Alarm. Attribution at bottom. 

#include "RTC.h"
#include <NTPClient.h>
#include <WiFiS3.h>
#include <ESP_Mail_Client.h>

int sensorPin = A0;   // setup data for Temperature Sensor - TMP36 
int sensorValue = 0;  // variable to store the value coming from the sensor
float volts;
float calibrationFactor = -0.036; // adjust volts down 0.036V, 3.6°C, and 6.5°F
float degreesC;
float degreesF;
float minDegreesF = 50.0;
int testHour = 12, timeUpdateHour = 9;
bool testSent = false, timeUpdated = false;
bool sendMessage = true; // send a notification on powerup. 
unsigned long unixTime;
unsigned long unixTimeLastSend = 0;
unsigned long minutesSinceLastSend;
unsigned long minMinutesBetweenSends = 15;

WiFiUDP Udp; // A UDP instance to let us send and receive packets over UDP
NTPClient timeClient(Udp);

#define WIFI_SSID "Freebox-78A090"
#define WIFI_PASS "xxmb7q6wxxxdd" // not needed with MAC address filtering

#define SMTP_HOST "smtp.gmail.com"
#define SMTP_PORT esp_mail_smtp_port_587
#define AUTHOR_EMAIL "Mon_Arduino"

#define AUTHOR_PASSWORD "urjyzylxxxxajzw"  // app password

#define RECIPIENT_EMAIL "xxxx@gmail.com" // @vtext.com turns an email into a Verizon text message. Other carriers have different addresses.

SMTPSession smtp;
void smtpCallback(SMTP_Status status); // Callback function to get the Email sending status
Session_Config config; // Declare the Session_Config for user defined session credentials
SMTP_Message message; // Declare the message class
RTCTime currentTime; // create a RTCTime object

void connectwifi(){
  Serial.begin(9600);
  //WiFi.begin(WIFI_SSID);  // WiFi.begin(WIFI_SSID) or 
  WiFi.begin(WIFI_SSID, WIFI_PASS); //depending on if password is necessary
  Serial.print("Connecting to Wi-Fi.");
  while (WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(300);
  }
  Serial.print(" Connected with IP: ");
  Serial.println(WiFi.localIP());
}

void setRTCtime(){
  RTC.begin();
  Serial.println("Starting connection to time server...");
  timeClient.begin();
  timeClient.update();
  auto timeZoneOffsetHours = -7; // change the time zone offset to your local one.
  auto unixTime = timeClient.getEpochTime() + (timeZoneOffsetHours * 3600);
  RTCTime timeToSet = RTCTime(unixTime);
  RTC.setTime(timeToSet);
  RTC.getTime(currentTime);
  Serial.println("Real Time Clock (RTC) set to: " + String(currentTime));
}

void getTempF(){
  float accumulator = 0;
  for (int i = 1; i <= 500; i++) {
    accumulator += analogRead(sensorPin);
  }
  sensorValue = accumulator / 500.0;
  volts = (float)sensorValue*5.0/1023.0 + calibrationFactor;
  degreesC = volts * 100.0 - 50.0;
  degreesF = degreesC * 9.0 / 5.0 + 32.0; // global var. no need to return. 
  Serial.println("Temp = " + String(degreesF, 1) + " Deg F");
}

void setupEmail(){
  config.server.host_name = SMTP_HOST; // Set the session config
  config.server.port = SMTP_PORT;
  config.login.email = AUTHOR_EMAIL;
  config.login.password = AUTHOR_PASSWORD;
  //config.login.user_domain = "";
  config.login.user_domain = F("127.0.0.1"); // not having this might have been causing a crash?         **** 

  message.sender.name = "Arduino"; // Setup the email message
  message.sender.email = AUTHOR_EMAIL;  
  message.clearRecipients();
  message.addRecipient(F("Andy"), RECIPIENT_EMAIL);

  if (degreesF < minDegreesF) { // finish setting up email variables
    message.subject = "ALARM";
  } else {
    message.subject = "Notification";
  }
  message.text.content = "Your Location Temp = " + String(degreesF, 1) + " Deg F";
 
  RTC.getTime(currentTime);
  float gmtOffset = 19.0; // GMT offset in hour (7 + 12 per Send_HTML.ino)
  smtp.setSystemTime(currentTime.getUnixTime(), gmtOffset);
}

void sendEmail(){
  smtp.setTCPTimeout(10); // not having this might have been causing a crash?                ****
  
  if (!smtp.connect(&config)){
    ESP_MAIL_PRINTF("Connection error, Status Code: %d, Error Code: %d, Reason: %s", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str());
    return;
  } else {
    Serial.println("smtp.connect successful");
  }
  
  if (!smtp.isLoggedIn()){
    Serial.println("\nNot yet logged in.");
    return;
  }
  else{
    if (smtp.isAuthenticated())
      Serial.println("\nSuccessfully logged in.");
    else
      Serial.println("\nConnected with no Auth.");
  }

  if (MailClient.sendMail(&smtp, &message)) {
    sendMessage = false;
    unixTimeLastSend = unixTime;
  } else {
    ESP_MAIL_PRINTF("Error, Status Code: %d, Error Code: %d, Reason: %s", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str());
  }
}

void setup(){
  connectwifi();
  setRTCtime();
  WiFi.disconnect();

  MailClient.networkReconnect(true);
  smtp.debug(1);
  smtp.callback(smtpCallback); // Set the callback function to get the sending results
}

void loop(){
  getTempF();
  RTC.getTime(currentTime);
  int hour = currentTime.getHour();
  unixTime = currentTime.getUnixTime();
  minutesSinceLastSend = (unixTime - unixTimeLastSend)/60;

  if (hour >= timeUpdateHour && timeUpdated == false){ // RTC on R4 drifts about 15 minutes per day. Update each morning.
      connectwifi();
      setRTCtime();
      WiFi.disconnect();
      timeUpdated = true;
  }
  if (hour < (timeUpdateHour-1) && timeUpdated == true) timeUpdated = false; // -1hr to prevent 2 updates if reset earlier a couple minutes. 

  if (hour >= testHour && testSent == false){ // set flag to send message if time and it hasn't been sent yet
    sendMessage = true;
    testSent = true;
  }
  if (hour < testHour && testSent == true) testSent = false; // reset trigger

  if (degreesF < minDegreesF) sendMessage = true; // set flag to send message if temperature is too low

  if (sendMessage == true && minutesSinceLastSend >= minMinutesBetweenSends) {
    setupEmail();
    connectwifi();
    sendEmail();
    //smtp.closeSession(); // could this be causing crash? not sure it is necessary. 
    WiFi.disconnect();
  }

  delay(60000); // about 1 minute
}

void smtpCallback(SMTP_Status status){
  Serial.println(status.info());
  if (status.success()){
    ESP_MAIL_PRINTF("Message sent success: %d\n", status.completedCount());
    ESP_MAIL_PRINTF("Message sent failed: %d\n", status.failedCount());
    for (size_t i = 0; i < smtp.sendingResult.size(); i++) {
      SMTP_Result result = smtp.sendingResult.getItem(i);
      ESP_MAIL_PRINTF("Message No: %d\n", i + 1);
      ESP_MAIL_PRINTF("Status: %s\n", result.completed ? "success" : "failed");
      ESP_MAIL_PRINTF("Date/Time: %s\n", MailClient.Time.getDateTimeString(result.timestamp, "%B %d, %Y %H:%M:%S").c_str());
      ESP_MAIL_PRINTF("Recipient: %s\n", result.recipients.c_str());
      ESP_MAIL_PRINTF("Subject: %s\n", result.subject.c_str());
    }
    Serial.println("----------------");
    smtp.sendingResult.clear(); // You need to clear sending result as the memory usage will grow up.
  }
}

/*
built based on examples provided by the following and many others:
Mobizt https://github.com/mobizt/ESP-Mail-Client/blob/master/examples/SMTP/Send_HTML/Send_HTML.ino
Rui Santos https://RandomNerdTutorials.com/esp32-send-email-smtp-server-arduino-ide/

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

je n'ai pas cette carte, je ne peux pas reproduire votre test. désolé
assurez vous d'avoir bien suivi toutes les étapes décrites dans la vidéo

Bonjour a tous
Pour information j'ai réglé mon problème. en faite je n'avais pas d'erreur dans le programme. Il s'agissait de Google gmail qui refusait. Donc j'ai crée un nouveau mail chez free et ça fonctionne impec. Si ça peut servir a d'autres
Serge

Je crois que gmail n'autorise plus les accès SMTP ou IMAP. ou alors avec un multi contrôle.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.