Site icon Renzo Mischianti

Nano 33 iot not sending basic gmail example

Hello, I have an Arduino Nano 33 iot. It can connect fine to my wifi network, tested using WiFiNINA's WPAConnect example. I modified the basic gmail example (under ESP32) to work with WiFiNINA. I also extracted all secret data to an external header file, Arduino secrets, where each is defined. The Code I have is:

#include "Arduino.h"
#include <EMailSender.h>
#include <WiFiNINA.h>
#include "arduino_secrets.h"

const char *ssid = SECRET_SSID;
const char *password = SECRET_PASS;

uint8_t connection_state = 0;
uint16_t reconnect_interval = 10000;
int i = 0;

const char *email_recp = EMAIL_RECIPIENT;

EMailSender emailSend(EMAIL_SENDER, EMAIL_PASS);

uint8_t WiFiConnect(const char *nSSID = nullptr,
		const char *nPassword = nullptr) {
	static uint16_t attempt = 0;
	Serial.print("Connecting to ");
	if (nSSID) {
		WiFi.begin(nSSID, nPassword);
		Serial.println(nSSID);
	}

	uint8_t i = 0;
	while (WiFi.status() != WL_CONNECTED && i++ < 50) {
		delay(200);
		Serial.print(".");
	}
	++attempt;
	Serial.println("");
	if (i == 51) {
		Serial.print("Connection: TIMEOUT on attempt: ");
		Serial.println(attempt);
		if (attempt % 2 == 0)
			Serial.println(
					"Check if access point available or SSID and Password\r\n");
		return false;
	}
	Serial.println("Connection: ESTABLISHED");
	Serial.print("Got IP address: ");
	Serial.println(WiFi.localIP());
	return true;
}
void Awaits() {
	uint32_t ts = millis();
	while (!connection_state) {
		delay(50);
		if (millis() > (ts + reconnect_interval) && !connection_state) {
			connection_state = WiFiConnect();
			ts = millis();
		}
	}
}

void sendEmail(String subjectStr, String messageStr) {
	EMailSender::EMailMessage message;
	message.subject = subjectStr;
	message.message = messageStr;
	byte statusB = 99;
	byte codeB = 99;
	while (statusB != 1 && codeB != 0) {
		EMailSender::Response resp = emailSend.send(email_recp, message);

		Serial.println("Sending status: ");
		Serial.println(resp.status);
		Serial.println(resp.code);
		Serial.println(resp.desc);
		if (WiFi.status() == WL_CONNECTED) {
			Serial.println("Connected to WiFi still");
		} else {
			Serial.println("Disconnected from WiFi");
		}
	}
}

void setup() {
	Serial.begin(115200);
	delay(1000);
	Serial.println("START!");
	connection_state = WiFiConnect(ssid, password);
	if (!connection_state) { // if not connected to WIFI
		Awaits(); // constantly trying to connect
	}
	String subject = "Testing " + i;
	sendEmail(subject, "This is the body of the message.");
}

void loop() {

}

This outputs:

Connection: ESTABLISHED

Got IP address: 192.168.1.149

Sending status:

0

2
Could not connect to mail server

Disconnected from WiFi

Sending status:

0
Exit mobile version