ESP32 Gmail

Trong hướng dẫn này, chúng ta sẽ học cách lập trình ESP32 để gửi email từ tài khoản Gmail của bạn. Người gửi email sẽ là tài khoản Gmail, và người nhận có thể là bất kỳ loại tài khoản email nào.

ESP32 gmail

Linh Kiện Cần Thiết

1×mô-đun phát triển ESP-WROOM-32
1×Alternatively, ESP32 Uno-form board
1×Alternatively, ESP32 S3 Uno-form board
1×Cáp USB Type-C
1×(Khuyến nghị) Screw Terminal Expansion Board for ESP32
1×(Khuyến nghị) Breakout Expansion Board for ESP32
1×(Khuyến nghị) Power Splitter for ESP32

Or you can buy the following kits:

1×DIYables ESP32 Starter Kit (ESP32 included)
1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)

Chuẩn Bị Trước

Chúng ta cần một tài khoản Gmail và mật khẩu ứng dụng tương ứng để sử dụng trong code. Dưới đây là những điểm quan trọng cần lưu ý:

  • Không sử dụng tài khoản Gmail hiện tại của bạn. Hãy tạo một tài khoản mới chuyên dụng cho việc thử nghiệm để tránh các vấn đề có thể xảy ra.
  • Mật khẩu được sử dụng trong code ESP32 không giống với mật khẩu bạn dùng để đăng nhập Gmail qua trình duyệt web. Bạn cần thực hiện một số bước để có được "App Password" từ Google Account.

Dưới đây là hướng dẫn từng bước:

gmail security
  • Bật 2-Step Verification (App passwords chỉ có thể được sử dụng với các tài khoản đã bật xác thực 2 bước).
  • Truy cập trang Google App Passwords và tạo một app password. Bạn có thể đặt bất kỳ tên nào.
google app passwords
  • Nhấp vào nút Create. Bạn sẽ nhận được mật khẩu 16 ký tự như thế này:
gmail app passwords
  • Sao chép và lưu trữ chuỗi 16 ký tự này. Nó sẽ được sử dụng trong code ESP32 ở phần tiếp theo.

※ Lưu ý:

Google có thể thay đổi giao diện người dùng theo thời gian. Nếu bạn làm theo các bước trên nhưng không thể có được "App Passwords," hãy thử tìm kiếm "How to get Google App Passwords" để có hướng dẫn mới nhất.

Code ESP32

/* * Mã ESP32 này được phát triển bởi newbiely.vn * Mã ESP32 này được cung cấp để sử dụng công khai, không có ràng buộc. * Để xem hướng dẫn chi tiết và sơ đồ kết nối, vui lòng truy cập: * https://newbiely.vn/tutorials/esp32/esp32-gmail */ #include <WiFi.h> #include <ESP_Mail_Client.h> #define WIFI_SSID "YOUR_WIFI_SSID" // CHANGE IT #define WIFI_PASSWORD "YOUR_WIFI_PASSWORD" // CHANGE IT // the sender email credentials #define SENDER_EMAIL "xxxxxx@gmail.com" // CHANGE IT #define SENDER_PASSWORD "xxxx xxxx xxxx xxxx" // CHANGE IT to your Google App password #define RECIPIENT_EMAIL "xxxxxx@gmail.com" // CHANGE IT #define SMTP_HOST "smtp.gmail.com" #define SMTP_PORT 587 SMTPSession smtp; void setup() { Serial.begin(9600); 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(); String subject = "Email Notification from ESP32"; String textMsg = "This is an email sent from ESP32.\n"; textMsg += "Sensor value: "; textMsg += "15"; // OR replace this value read from a sensor gmail_send(subject, textMsg); } void loop() { // YOUR OTHER CODE HERE } void gmail_send(String subject, String textMsg) { // set the network reconnection option MailClient.networkReconnect(true); smtp.debug(1); smtp.callback(smtpCallback); Session_Config config; // set the session config config.server.host_name = SMTP_HOST; config.server.port = SMTP_PORT; config.login.email = SENDER_EMAIL; config.login.password = SENDER_PASSWORD; config.login.user_domain = F("127.0.0.1"); 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("ESP32"); message.sender.email = SENDER_EMAIL; message.subject = subject; message.addRecipient(F("To Whom It May Concern"), RECIPIENT_EMAIL); message.text.content = textMsg; message.text.transfer_encoding = "base64"; message.text.charSet = F("utf-8"); message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low; // set the custom message header message.addHeader(F("Message-ID: <abcde.fghij@gmail.com>")); // connect to the server if (!smtp.connect(&config)) { Serial.printf("Connection error, Status Code: %d, Error Code: %d, Reason: %s\n", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str()); return; } if (!smtp.isLoggedIn()) { Serial.println("Not yet logged in."); } else { if (smtp.isAuthenticated()) Serial.println("Successfully logged in."); else Serial.println("Connected with no Auth."); } // start sending Email and close the session if (!MailClient.sendMail(&smtp, &message)) Serial.printf("Error, Status Code: %d, Error Code: %d, Reason: %s\n", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str()); } // 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()) { Serial.println("----------------"); Serial.printf("Message sent success: %d\n", status.completedCount()); Serial.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); Serial.printf("Message No: %d\n", i + 1); Serial.printf("Status: %s\n", result.completed ? "success" : "failed"); Serial.printf("Date/Time: %s\n", MailClient.Time.getDateTimeString(result.timestamp, "%B %d, %Y %H:%M:%S").c_str()); Serial.printf("Recipient: %s\n", result.recipients.c_str()); Serial.printf("Subject: %s\n", result.subject.c_str()); } Serial.println("----------------\n"); // free the memory smtp.sendingResult.clear(); } }

Các Bước Thực Hiện

  • Nếu đây là lần đầu tiên bạn sử dụng ESP32, hãy xem ESP32 - Cài Đặt Phần Mềm.
  • Kết nối bo mạch ESP32 với PC qua cáp USB
  • Mở Arduino IDE trên PC của bạn.
  • Chọn đúng bo mạch ESP32 (ví dụ: ESP32 Dev Module) và cổng COM.
  • Mở Library Manager bằng cách nhấp vào biểu tượng Library Manager trên thanh điều hướng bên trái của Arduino IDE.
  • Tìm kiếm ESP Mail Client, sau đó tìm ESP Mail Client được tạo bởi Mobizt.
  • Nhấp vào nút Install để cài đặt thư viện ESP Mail Client.
ESP32 esp mail client thư viện
  • Sao chép code trên và mở bằng Arduino IDE
  • Thay đổi thông tin WiFi (SSID và password) trong code thành thông tin của bạn bằng cách thay đổi hai hằng số WIFI_SSIDWIFI_PASSWORD
  • Thay đổi email người gửi và mật khẩu trong code thành thông tin của bạn bằng cách thay đổi hai hằng số SENDER_EMAILSENDER_PASSWORD
  • Thay đổi email người nhận trong code thành email của bạn bằng cách thay đổi hằng số RECIPIENT_EMAIL. Email người nhận có thể giống với email người gửi

※ Lưu ý:

  • Email người gửi PHẢI là Gmail
  • Mật khẩu người gửi là App passwords bạn đã lấy từ bước trước
  • Email người nhận có thể là bất kỳ loại email nào
  • Nhấp vào nút Upload trên Arduino IDE để tải code lên ESP32
  • Mở Serial Monitor
  • Kiểm tra kết quả trên Serial Monitor.
COM6
Send
#### Message sent successfully > C: message sent successfully ---------------- Message sent success: 1 Message sent failed: 0 ---------------- Message No: 1 Status: success Date/Time: May 27, 2024 04:42:50 Recipient: xxxxxx@gmail.com Subject: Email Notification from ESP32 ----------------
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  
  • Kiểm tra hộp thư email người nhận của bạn. Bạn sẽ nhận được email như bên dưới:
ESP32 sends email

Video Tutorial

Việc sản xuất video tốn rất nhiều thời gian. Nếu video hướng dẫn hữu ích cho việc học của bạn, hãy đăng ký kênh YouTube để ủng hộ. Nếu nhu cầu đủ cao, chúng tôi sẽ cố gắng làm thêm nhiều video.