在你的 Arduino 代码中,你需要设置 ESP8266 连接到你的 Wi-Fi 网络。你需要提供网络名称(SSID)和密码。
- #include <ESP8266WiFi.h>
- const char* ssid = "YourWiFiNetworkName";
- const char* password = "YourWiFiPassword";
- void setup() {
- Serial.begin(115200);
- delay(10);
- // Connect to Wi-Fi network
- Serial.println();
- Serial.println();
- Serial.print("Connecting to ");
- Serial.println(ssid);
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.print(".");
- }
- Serial.println("");
- Serial.println("WiFi connected");
- Serial.println("IP address: ");
- Serial.println(WiFi.localIP());
- }
- void loop() {
- // Your code here
- }
使用SMTP协议发送电子邮件:
一旦你的 ESP8266 连接到了 Wi-Fi 网络,你可以使用 SMTP 协议将电子邮件发送到指定的服务器。你需要设置 SMTP 服务器的地址、端口、电子邮件地址和密码,以及收件人的地址。
以下是一个简单的示例,假设你使用 Gmail 的 SMTP 服务器来发送邮件。
- #include <ESP8266WiFi.h>
- #include <WiFiClientSecure.h>
- const char* ssid = "YourWiFiNetworkName";
- const char* password = "YourWiFiPassword";
- const char* smtpServer = "smtp.gmail.com";
- const int smtpPort = 465;
- const char* email = "your_email@gmail.com";
- const char* password = "your_email_password";
- const char* recipient = "recipient_email@example.com";
- void setup() {
- Serial.begin(115200);
- delay(10);
- // Connect to Wi-Fi network
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.print(".");
- }
- Serial.println("");
- Serial.println("WiFi connected");
- Serial.println("IP address: ");
- Serial.println(WiFi.localIP());
- }
- void loop() {
- WiFiClientSecure client;
- if (client.connect(smtpServer, smtpPort)) {
- Serial.println("Connected to SMTP server");
- client.println("EHLO " + WiFi.localIP().toString());
- client.println("AUTH LOGIN");
- client.println(base64::encode(email));
- client.println(base64::encode(password));
- client.println("MAIL FROM:<" + String(email) + ">");
- client.println("RCPT TO:<" + String(recipient) + ">");
- client.println("DATA");
- client.println("Subject: Test Email from ESP8266");
- client.println();
- client.println("This is a test email sent from an ESP8266!");
- client.println(".");
- client.println("QUIT");
- Serial.println("Email sent");
- } else {
- Serial.println("Failed to connect to SMTP server");
- }
- delay(60000); // Send email every minute (for example)
- }
|