这几天想做一个报警项目,通过esp8266简单wifi协议进行邮件发送,首先还是来看看官方示例有没有合适的。有些童鞋没有的话,可以去下载官方库 ESP Mail Client等。
示例源码如下
/** * This example will send the Email in * the html version. * * * Created by K. Suwatchai (Mobizt) * * Email: suwatchai@outlook.com * * Github: https://github.com/mobizt/ESP-Mail-Client * * Copyright (c) 2021 mobizt * */ //To use send Email for Gmail to port 465 (SSL), less secure app option should be enabled. https://myaccount.google.com/lesssecureapps?pli=1 #include <Arduino.h> #if defined(ESP32) #include <WiFi.h> #elif defined(ESP8266) #include <ESP8266WiFi.h> #endif #include <ESP_Mail_Client.h> #define WIFI_SSID "<ssid>" #define WIFI_PASSWORD "<password>" /** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com * For yahoo mail, log in to your yahoo mail in web browser and generate app password by go to * https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc * and use the app password as password with your yahoo mail account to login. * The google app password signin is also available https://support.google.com/mail/answer/185833?hl=en */ #define SMTP_HOST "<host>" /** The smtp port e.g. * 25 or esp_mail_smtp_port_25 * 465 or esp_mail_smtp_port_465 * 587 or esp_mail_smtp_port_587 */ #define SMTP_PORT esp_mail_smtp_port_587 /* The log in credentials */ #define AUTHOR_EMAIL "<email>" #define AUTHOR_PASSWORD "<password>" /* The SMTP Session object used for Email sending */ SMTPSession smtp; /* Callback function to get the Email sending status */ void smtpCallback(SMTP_Status status); void setup() { Serial.begin(115200); #if defined(ARDUINO_ARCH_SAMD) while (!Serial) ; Serial.println(); Serial.println("**** Custom built WiFiNINA firmware need to be installed.****\nTo install firmware, read the instruction here, https://github.com/mobizt/ESP-Mail-Client#install-custom-built-wifinina-firmware"); #endif Serial.println(); Serial.print("Connecting to AP"); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(200); } Serial.println(""); Serial.println("WiFi connected."); Serial.println("IP address: "); Serial.println(WiFi.localIP()); Serial.println(); /** Enable the debug via Serial port * none debug or 0 * basic debug or 1 * * 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 data */ ESP_Mail_Session session; /** ######################################################## * Some properties of SMTPSession data and parameters pass to * SMTP_Message class accept the pointer to constant char * i.e. const char*. * * You may assign a string literal to that properties or function * like below example. * * session.login.user_domain = "mydomain.net"; * session.login.user_domain = String("mydomain.net").c_str(); * * or * * String doman = "mydomain.net"; * session.login.user_domain = domain.c_str(); * * And * * String name = "Jack " + String("dawson"); * String email = "jack_dawson" + String(123) + "@mail.com"; * * message.addRecipient(name.c_str(), email.c_str()); * * message.addHeader(String("Message-ID: <abcde.fghij@gmail.com>").c_str()); * * or * * String header = "Message-ID: <abcde.fghij@gmail.com>"; * message.addHeader(header.c_str()); * * ########################################################### */ /* Set the session config */ session.server.host_name = SMTP_HOST; session.server.port = SMTP_PORT; session.login.email = AUTHOR_EMAIL; session.login.password = AUTHOR_PASSWORD; session.login.user_domain = "mydomain.net"; /* Declare the message class */ SMTP_Message message; /* Set the message headers */ message.sender.name = "ESP Mail"; message.sender.email = AUTHOR_EMAIL; message.subject = "Test sending html Email"; message.addRecipient("Admin", "####@#####_dot_com"); String htmlMsg = "<p>This is the <span style=\"color:#ff0000;\">html text</span> message.</p><p>The message was sent via ESP device.</p>"; message.html.content = htmlMsg.c_str(); /** The html text message character set e.g. * us-ascii * utf-8 * utf-7 * The default value is utf-8 */ message.html.charSet = "us-ascii"; /** The content transfer encoding e.g. * enc_7bit or "7bit" (not encoded) * enc_qp or "quoted-printable" (encoded) * enc_base64 or "base64" (encoded) * enc_binary or "binary" (not encoded) * enc_8bit or "8bit" (not encoded) * The default value is "7bit" */ message.html.transfer_encoding = Content_Transfer_Encoding::enc_7bit; /** The message priority * esp_mail_smtp_priority_high or 1 * esp_mail_smtp_priority_normal or 3 * esp_mail_smtp_priority_low or 5 * The default value is esp_mail_smtp_priority_low */ message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low; /** The Delivery Status Notifications e.g. * esp_mail_smtp_notify_never * esp_mail_smtp_notify_success * esp_mail_smtp_notify_failure * esp_mail_smtp_notify_delay * The default value is esp_mail_smtp_notify_never */ //message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay; /* Set the custom message header */ message.addHeader("Message-ID: <abcde.fghij@gmail.com>"); /* Connect to server with the session config */ if (!smtp.connect(&session)) return; /* Start sending Email and close the session */ if (!MailClient.sendMail(&smtp, &message)) Serial.println("Error sending Email, " + smtp.errorReason()); //to clear sending result log //smtp.sendingResult.clear(); ESP_MAIL_PRINTF("Free Heap: %d\n", MailClient.getFreeHeap()); } 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()) { Serial.println("----------------"); ESP_MAIL_PRINTF("Message sent success: %d\n", status.completedCount()); ESP_MAIL_PRINTF("Message sent failled: %d\n", status.failedCount()); Serial.println("----------------\n"); struct tm dt; for (size_t i = 0; i < smtp.sendingResult.size(); i++) { /* Get the result item */ SMTP_Result result = smtp.sendingResult.getItem(i); time_t ts = (time_t)result.timestamp; localtime_r(&ts, &dt); ESP_MAIL_PRINTF("Message No: %d\n", i + 1); ESP_MAIL_PRINTF("Status: %s\n", result.completed ? "success" : "failed"); ESP_MAIL_PRINTF("Date/Time: %d/%d/%d %d:%d:%d\n", dt.tm_year + 1900, dt.tm_mon + 1, dt.tm_mday, dt.tm_hour, dt.tm_min, dt.tm_sec); ESP_MAIL_PRINTF("Recipient: %s\n", result.recipients); ESP_MAIL_PRINTF("Subject: %s\n", result.subject); } Serial.println("----------------\n"); //You need to clear sending result as the memory usage will grow up as it keeps the status, timstamp and //pointer to const char of recipients and subject that user assigned to the SMTP_Message object. //Because of pointer to const char that stores instead of dynamic string, the subject and recipients value can be //a garbage string (pointer points to undefind location) as SMTP_Message was declared as local variable or the value changed. //smtp.sendingResult.clear(); } }
用自己126/163邮箱试了一下,发送不成功,因为端口监视器没有截图,大致信息就是没有权限登陆进行操作,后来发现自己126/163的SMTP第三方客户端登陆授全没开,具体怎么开大家可以百度一下。(这操作挺简单的,这里发邮件只开一个IMAP/SMTP,POP3想开启也可,两个有啥区别,这里不做解释,大家自己百度)
后面在使用官方示例,发现还是出问题,这里考虑到可能是授权码原因,重新在GitHub找了示例。我再次基础上进行修改了一下。毕竟也是开源的,因为自己项目需要,这里
#include <Arduino.h> #if defined(ESP32) #include <WiFi.h> #elif defined(ESP8266) #include <ESP8266WiFi.h> #endif #include <ESP_Mail_Client.h> #define WIFI_SSID "ssid自己的wifi" #define WIFI_PASSWORD "PWD 密码" //定义 #define SMTP_HOST "smtp.126.com" //定义端口,一般SSL 465 非SSL 25,其他的自己自行百度 #define SMTP_PORT 465 #define AUTHOR_EMAIL "自己发送邮箱账号@xxx.com" //很多大佬给出怎么去找授权码,但没有告知授权码填哪里,这里大家注意了,授权码就是填在PASSword里 #define AUTHOR_PASSWORD "这里授权码" //网易的是16位,其他的邮箱自己去看 #define RECIPIENT_EMAIL "接受者邮箱账号@xx.com" SMTPSession smtp; ESP_Mail_Session session; /* 注册回调函数,获取邮件发送状态 */ /* 定义 smtp session 对象*/ /* 获取邮件发送状态的回调函数 */ void getSmtpStatusCallback(SMTP_Status status); /* 获取发送状态的回调函数 */ //这里大家不用看,我自己部分项目 /*int XXX = 12; int XXXX = 13; float XXXX; float XXXXXX; */ void setup(){ Serial.begin(115200); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); while (WiFi.status() != WL_CONNECTED){ delay(200); } Serial.println("WiFi 连接成功."); Serial.println("IP 地址: "); Serial.println(WiFi.localIP()); pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output pinMode(echoPin, INPUT); // Sets the echoPin as an Input /* smtp开启debug,debug信息输出到串口 */ SMTP_Message message; } //邮件发送模块 void alarm(){ smtp.debug(1); SMTP_Message message; /* 设置smtp 相关参数, host, port等 */ session.server.host_name = SMTP_HOST; session.server.port = SMTP_PORT; session.login.email = AUTHOR_EMAIL; session.login.password = AUTHOR_PASSWORD; session.login.user_domain = ""; /* 定义smtp message消息类 */ /* 定义邮件消息类的名称,发件人,标题和添加收件人 */ message.sender.name = "发送者名字"; message.sender.email = AUTHOR_EMAIL; message.subject = "主题"; message.addRecipient("接受者名字随便填", RECIPIENT_EMAIL); /* 设置message html 格式和内容*/ String htmlMsg = String(distance, DEC); 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; /* 连接smtp服务器 */ if (!smtp.connect(&session)) return; /* 调用发送邮件函数,失败的话,获取失败信息 */ if (!MailClient.sendMail(&smtp, &message)) Serial.println("Fail to sending , " + smtp.errorReason()); } void loop(){ /*这里大家也可以忽略 digitalWrite(XXX, LOW); delayMicroseconds(2); digitalWrite(XXX, HIGH); delayMicroseconds(2); digitalWrite(XXX, LOW); XXX= pulseIn(XXXXX, HIGH); Serial.println(XXXXXXX); */ if (邮件发送需要触发的条件){ alarm(); } delay(200); } void getSmtpStatusCallback(SMTP_Status status){ /* 输出邮件发送状态信息 */ Serial.println(status.info()); /*状态获取成功,打印状态信息 */ if (status.success()){ Serial.println("----------------"); ESP_MAIL_PRINTF("邮件发送成功个数: %d\n", status.completedCount()); ESP_MAIL_PRINTF("邮件发送失败个数: %d\n", status.failedCount()); struct tm dt; for (size_t i = 0; i < smtp.sendingResult.size(); i++){ /* 依次获取发送邮件状态 */ SMTP_Result result = smtp.sendingResult.getItem(i); time_t ts = (time_t)result.timestamp; localtime_r(&ts, &dt); ESP_MAIL_PRINTF("收件人: %s邮件发送状态信息\n", result.recipients); ESP_MAIL_PRINTF("状态: %s\n", result.completed ? "success" : "failed"); ESP_MAIL_PRINTF("发送时间: %d/%d/%d %d:%d:%d\n", dt.tm_year + 1900, dt.tm_mon + 1, dt.tm_mday, dt.tm_hour, dt.tm_min, dt.tm_sec); ESP_MAIL_PRINTF("邮件标题: %s\n", result.subject); } } }
上面就是使用ESP8266发送邮件Send Email模块源码,里面重新补充了解释,因为项目需要,通过某些条件进行调用发邮件函数,邮件发送响应比较快,个人推荐使用,测试下很稳定。
希望可以帮助一些正在学习esp8266朋友,尽自己一份绵薄之力,感谢那些开源的大佬...