smtp_client_example_main.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. /**
  2. * SMTP email client
  3. *
  4. * Adapted from the `ssl_mail_client` example in mbedtls.
  5. *
  6. * Original Copyright (C) 2006-2016, ARM Limited, All Rights Reserved, Apache 2.0 License.
  7. * Additions Copyright (C) Copyright 2015-2020 Espressif Systems (Shanghai) PTE LTD, Apache 2.0 License.
  8. *
  9. *
  10. * Licensed under the Apache License, Version 2.0 (the "License");
  11. * you may not use this file except in compliance with the License.
  12. * You may obtain a copy of the License at
  13. *
  14. * http://www.apache.org/licenses/LICENSE-2.0
  15. *
  16. * Unless required by applicable law or agreed to in writing, software
  17. * distributed under the License is distributed on an "AS IS" BASIS,
  18. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. * See the License for the specific language governing permissions and
  20. * limitations under the License.
  21. */
  22. #include <string.h>
  23. #include <stdlib.h>
  24. #include "freertos/FreeRTOS.h"
  25. #include "freertos/task.h"
  26. #include "esp_event.h"
  27. #include "esp_log.h"
  28. #include "esp_system.h"
  29. #include "nvs_flash.h"
  30. #include "protocol_examples_common.h"
  31. #include "mbedtls/platform.h"
  32. #include "mbedtls/net_sockets.h"
  33. #include "mbedtls/esp_debug.h"
  34. #include "mbedtls/ssl.h"
  35. #include "mbedtls/entropy.h"
  36. #include "mbedtls/ctr_drbg.h"
  37. #include "mbedtls/error.h"
  38. #include "mbedtls/certs.h"
  39. #include <mbedtls/base64.h>
  40. #include <sys/param.h>
  41. /* Constants that are configurable in menuconfig */
  42. #define MAIL_SERVER CONFIG_SMTP_SERVER
  43. #define MAIL_PORT CONFIG_SMTP_PORT_NUMBER
  44. #define SENDER_MAIL CONFIG_SMTP_SENDER_MAIL
  45. #define SENDER_PASSWORD CONFIG_SMTP_SENDER_PASSWORD
  46. #define RECIPIENT_MAIL CONFIG_SMTP_RECIPIENT_MAIL
  47. #define SERVER_USES_STARTSSL 1
  48. static const char *TAG = "smtp_example";
  49. #define TASK_STACK_SIZE (8 * 1024)
  50. #define BUF_SIZE 512
  51. #define VALIDATE_MBEDTLS_RETURN(ret, min_valid_ret, max_valid_ret, goto_label) \
  52. do { \
  53. if (ret < min_valid_ret || ret > max_valid_ret) { \
  54. goto goto_label; \
  55. } \
  56. } while (0) \
  57. /**
  58. * Root cert for smtp.googlemail.com, taken from server_root_cert.pem
  59. *
  60. * The PEM file was extracted from the output of this command:
  61. * openssl s_client -showcerts -connect smtp.googlemail.com:587 -starttls smtp
  62. *
  63. * The CA root cert is the last cert given in the chain of certs.
  64. *
  65. * To embed it in the app binary, the PEM file is named
  66. * in the component.mk COMPONENT_EMBED_TXTFILES variable.
  67. */
  68. extern const uint8_t server_root_cert_pem_start[] asm("_binary_server_root_cert_pem_start");
  69. extern const uint8_t server_root_cert_pem_end[] asm("_binary_server_root_cert_pem_end");
  70. extern const uint8_t esp_logo_png_start[] asm("_binary_esp_logo_png_start");
  71. extern const uint8_t esp_logo_png_end[] asm("_binary_esp_logo_png_end");
  72. static int write_and_get_response(mbedtls_net_context *sock_fd, unsigned char *buf, size_t len)
  73. {
  74. int ret;
  75. const size_t DATA_SIZE = 128;
  76. unsigned char data[DATA_SIZE];
  77. char code[4];
  78. size_t i, idx = 0;
  79. if (len) {
  80. ESP_LOGD(TAG, "%s", buf);
  81. }
  82. if (len && (ret = mbedtls_net_send(sock_fd, buf, len)) <= 0) {
  83. ESP_LOGE(TAG, "mbedtls_net_send failed with error -0x%x", -ret);
  84. return ret;
  85. }
  86. do {
  87. len = DATA_SIZE - 1;
  88. ret = mbedtls_net_recv(sock_fd, data, len);
  89. if (ret <= 0) {
  90. ESP_LOGE(TAG, "mbedtls_net_recv failed with error -0x%x", -ret);
  91. goto exit;
  92. }
  93. data[len] = '\0';
  94. printf("\n%s", data);
  95. len = ret;
  96. for (i = 0; i < len; i++) {
  97. if (data[i] != '\n') {
  98. if (idx < 4) {
  99. code[idx++] = data[i];
  100. }
  101. continue;
  102. }
  103. if (idx == 4 && code[0] >= '0' && code[0] <= '9' && code[3] == ' ') {
  104. code[3] = '\0';
  105. ret = atoi(code);
  106. goto exit;
  107. }
  108. idx = 0;
  109. }
  110. } while (1);
  111. exit:
  112. return ret;
  113. }
  114. static int write_ssl_and_get_response(mbedtls_ssl_context *ssl, unsigned char *buf, size_t len)
  115. {
  116. int ret;
  117. const size_t DATA_SIZE = 128;
  118. unsigned char data[DATA_SIZE];
  119. char code[4];
  120. size_t i, idx = 0;
  121. if (len) {
  122. ESP_LOGD(TAG, "%s", buf);
  123. }
  124. while (len && (ret = mbedtls_ssl_write(ssl, buf, len)) <= 0) {
  125. if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  126. ESP_LOGE(TAG, "mbedtls_ssl_write failed with error -0x%x", -ret);
  127. goto exit;
  128. }
  129. }
  130. do {
  131. len = DATA_SIZE - 1;
  132. ret = mbedtls_ssl_read(ssl, data, len);
  133. if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  134. continue;
  135. }
  136. if (ret <= 0) {
  137. ESP_LOGE(TAG, "mbedtls_ssl_read failed with error -0x%x", -ret);
  138. goto exit;
  139. }
  140. ESP_LOGD(TAG, "%s", data);
  141. len = ret;
  142. for (i = 0; i < len; i++) {
  143. if (data[i] != '\n') {
  144. if (idx < 4) {
  145. code[idx++] = data[i];
  146. }
  147. continue;
  148. }
  149. if (idx == 4 && code[0] >= '0' && code[0] <= '9' && code[3] == ' ') {
  150. code[3] = '\0';
  151. ret = atoi(code);
  152. goto exit;
  153. }
  154. idx = 0;
  155. }
  156. } while (1);
  157. exit:
  158. return ret;
  159. }
  160. static int write_ssl_data(mbedtls_ssl_context *ssl, unsigned char *buf, size_t len)
  161. {
  162. int ret;
  163. if (len) {
  164. ESP_LOGD(TAG, "%s", buf);
  165. }
  166. while (len && (ret = mbedtls_ssl_write(ssl, buf, len)) <= 0) {
  167. if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  168. ESP_LOGE(TAG, "mbedtls_ssl_write failed with error -0x%x", -ret);
  169. return ret;
  170. }
  171. }
  172. return 0;
  173. }
  174. static int perform_tls_handshake(mbedtls_ssl_context *ssl)
  175. {
  176. int ret = -1;
  177. uint32_t flags;
  178. char *buf = NULL;
  179. buf = (char *) calloc(1, BUF_SIZE);
  180. if (buf == NULL) {
  181. ESP_LOGE(TAG, "calloc failed for size %d", BUF_SIZE);
  182. goto exit;
  183. }
  184. ESP_LOGI(TAG, "Performing the SSL/TLS handshake...");
  185. fflush(stdout);
  186. while ((ret = mbedtls_ssl_handshake(ssl)) != 0) {
  187. if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  188. ESP_LOGE(TAG, "mbedtls_ssl_handshake returned -0x%x", -ret);
  189. goto exit;
  190. }
  191. }
  192. ESP_LOGI(TAG, "Verifying peer X.509 certificate...");
  193. if ((flags = mbedtls_ssl_get_verify_result(ssl)) != 0) {
  194. /* In real life, we probably want to close connection if ret != 0 */
  195. ESP_LOGW(TAG, "Failed to verify peer certificate!");
  196. mbedtls_x509_crt_verify_info(buf, BUF_SIZE, " ! ", flags);
  197. ESP_LOGW(TAG, "verification info: %s", buf);
  198. } else {
  199. ESP_LOGI(TAG, "Certificate verified.");
  200. }
  201. ESP_LOGI(TAG, "Cipher suite is %s", mbedtls_ssl_get_ciphersuite(ssl));
  202. ret = 0; /* No error */
  203. exit:
  204. if (buf) {
  205. free(buf);
  206. }
  207. return ret;
  208. }
  209. static void smtp_client_task(void *pvParameters)
  210. {
  211. char *buf = NULL;
  212. unsigned char base64_buffer[128];
  213. int ret, len;
  214. size_t base64_len;
  215. mbedtls_entropy_context entropy;
  216. mbedtls_ctr_drbg_context ctr_drbg;
  217. mbedtls_ssl_context ssl;
  218. mbedtls_x509_crt cacert;
  219. mbedtls_ssl_config conf;
  220. mbedtls_net_context server_fd;
  221. mbedtls_ssl_init(&ssl);
  222. mbedtls_x509_crt_init(&cacert);
  223. mbedtls_ctr_drbg_init(&ctr_drbg);
  224. ESP_LOGI(TAG, "Seeding the random number generator");
  225. mbedtls_ssl_config_init(&conf);
  226. mbedtls_entropy_init(&entropy);
  227. if ((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
  228. NULL, 0)) != 0) {
  229. ESP_LOGE(TAG, "mbedtls_ctr_drbg_seed returned -0x%x", -ret);
  230. goto exit;
  231. }
  232. ESP_LOGI(TAG, "Loading the CA root certificate...");
  233. ret = mbedtls_x509_crt_parse(&cacert, server_root_cert_pem_start,
  234. server_root_cert_pem_end - server_root_cert_pem_start);
  235. if (ret < 0) {
  236. ESP_LOGE(TAG, "mbedtls_x509_crt_parse returned -0x%x", -ret);
  237. goto exit;
  238. }
  239. ESP_LOGI(TAG, "Setting hostname for TLS session...");
  240. /* Hostname set here should match CN in server certificate */
  241. if ((ret = mbedtls_ssl_set_hostname(&ssl, MAIL_SERVER)) != 0) {
  242. ESP_LOGE(TAG, "mbedtls_ssl_set_hostname returned -0x%x", -ret);
  243. goto exit;
  244. }
  245. ESP_LOGI(TAG, "Setting up the SSL/TLS structure...");
  246. if ((ret = mbedtls_ssl_config_defaults(&conf,
  247. MBEDTLS_SSL_IS_CLIENT,
  248. MBEDTLS_SSL_TRANSPORT_STREAM,
  249. MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
  250. ESP_LOGE(TAG, "mbedtls_ssl_config_defaults returned -0x%x", -ret);
  251. goto exit;
  252. }
  253. mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  254. mbedtls_ssl_conf_ca_chain(&conf, &cacert, NULL);
  255. mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg);
  256. #ifdef CONFIG_MBEDTLS_DEBUG
  257. mbedtls_esp_enable_debug_log(&conf, 4);
  258. #endif
  259. if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0) {
  260. ESP_LOGE(TAG, "mbedtls_ssl_setup returned -0x%x", -ret);
  261. goto exit;
  262. }
  263. mbedtls_net_init(&server_fd);
  264. ESP_LOGI(TAG, "Connecting to %s:%s...", MAIL_SERVER, MAIL_PORT);
  265. if ((ret = mbedtls_net_connect(&server_fd, MAIL_SERVER,
  266. MAIL_PORT, MBEDTLS_NET_PROTO_TCP)) != 0) {
  267. ESP_LOGE(TAG, "mbedtls_net_connect returned -0x%x", -ret);
  268. goto exit;
  269. }
  270. ESP_LOGI(TAG, "Connected.");
  271. mbedtls_ssl_set_bio(&ssl, &server_fd, mbedtls_net_send, mbedtls_net_recv, NULL);
  272. buf = (char *) calloc(1, BUF_SIZE);
  273. if (buf == NULL) {
  274. ESP_LOGE(TAG, "calloc failed for size %d", BUF_SIZE);
  275. goto exit;
  276. }
  277. #if SERVER_USES_STARTSSL
  278. /* Get response */
  279. ret = write_and_get_response(&server_fd, (unsigned char *) buf, 0);
  280. VALIDATE_MBEDTLS_RETURN(ret, 200, 299, exit);
  281. ESP_LOGI(TAG, "Writing EHLO to server...");
  282. len = snprintf((char *) buf, BUF_SIZE, "EHLO %s\r\n", "ESP32");
  283. ret = write_and_get_response(&server_fd, (unsigned char *) buf, len);
  284. VALIDATE_MBEDTLS_RETURN(ret, 200, 299, exit);
  285. ESP_LOGI(TAG, "Writing STARTTLS to server...");
  286. len = snprintf((char *) buf, BUF_SIZE, "STARTTLS\r\n");
  287. ret = write_and_get_response(&server_fd, (unsigned char *) buf, len);
  288. VALIDATE_MBEDTLS_RETURN(ret, 200, 299, exit);
  289. ret = perform_tls_handshake(&ssl);
  290. if (ret != 0) {
  291. goto exit;
  292. }
  293. #else /* SERVER_USES_STARTSSL */
  294. ret = perform_tls_handshake(&ssl);
  295. if (ret != 0) {
  296. goto exit;
  297. }
  298. /* Get response */
  299. ret = write_ssl_and_get_response(&ssl, (unsigned char *) buf, 0);
  300. VALIDATE_MBEDTLS_RETURN(ret, 200, 299, exit);
  301. ESP_LOGI(TAG, "Writing EHLO to server...");
  302. len = snprintf((char *) buf, BUF_SIZE, "EHLO %s\r\n", "ESP32");
  303. ret = write_ssl_and_get_response(&ssl, (unsigned char *) buf, len);
  304. VALIDATE_MBEDTLS_RETURN(ret, 200, 299, exit);
  305. #endif /* SERVER_USES_STARTSSL */
  306. /* Authentication */
  307. ESP_LOGI(TAG, "Authentication...");
  308. ESP_LOGI(TAG, "Write AUTH LOGIN");
  309. len = snprintf( (char *) buf, BUF_SIZE, "AUTH LOGIN\r\n" );
  310. ret = write_ssl_and_get_response(&ssl, (unsigned char *) buf, len);
  311. VALIDATE_MBEDTLS_RETURN(ret, 200, 399, exit);
  312. ESP_LOGI(TAG, "Write USER NAME");
  313. ret = mbedtls_base64_encode((unsigned char *) base64_buffer, sizeof(base64_buffer),
  314. &base64_len, (unsigned char *) SENDER_MAIL, strlen(SENDER_MAIL));
  315. if (ret != 0) {
  316. ESP_LOGE(TAG, "Error in mbedtls encode! ret = -0x%x", -ret);
  317. goto exit;
  318. }
  319. len = snprintf((char *) buf, BUF_SIZE, "%s\r\n", base64_buffer);
  320. ret = write_ssl_and_get_response(&ssl, (unsigned char *) buf, len);
  321. VALIDATE_MBEDTLS_RETURN(ret, 300, 399, exit);
  322. ESP_LOGI(TAG, "Write PASSWORD");
  323. ret = mbedtls_base64_encode((unsigned char *) base64_buffer, sizeof(base64_buffer),
  324. &base64_len, (unsigned char *) SENDER_PASSWORD, strlen(SENDER_PASSWORD));
  325. if (ret != 0) {
  326. ESP_LOGE(TAG, "Error in mbedtls encode! ret = -0x%x", -ret);
  327. goto exit;
  328. }
  329. len = snprintf((char *) buf, BUF_SIZE, "%s\r\n", base64_buffer);
  330. ret = write_ssl_and_get_response(&ssl, (unsigned char *) buf, len);
  331. VALIDATE_MBEDTLS_RETURN(ret, 200, 399, exit);
  332. /* Compose email */
  333. ESP_LOGI(TAG, "Write MAIL FROM");
  334. len = snprintf((char *) buf, BUF_SIZE, "MAIL FROM:<%s>\r\n", SENDER_MAIL);
  335. ret = write_ssl_and_get_response(&ssl, (unsigned char *) buf, len);
  336. VALIDATE_MBEDTLS_RETURN(ret, 200, 299, exit);
  337. ESP_LOGI(TAG, "Write RCPT");
  338. len = snprintf((char *) buf, BUF_SIZE, "RCPT TO:<%s>\r\n", RECIPIENT_MAIL);
  339. ret = write_ssl_and_get_response(&ssl, (unsigned char *) buf, len);
  340. VALIDATE_MBEDTLS_RETURN(ret, 200, 299, exit);
  341. ESP_LOGI(TAG, "Write DATA");
  342. len = snprintf((char *) buf, BUF_SIZE, "DATA\r\n");
  343. ret = write_ssl_and_get_response(&ssl, (unsigned char *) buf, len);
  344. VALIDATE_MBEDTLS_RETURN(ret, 300, 399, exit);
  345. ESP_LOGI(TAG, "Write Content");
  346. /* We do not take action if message sending is partly failed. */
  347. len = snprintf((char *) buf, BUF_SIZE,
  348. "From: %s\r\nSubject: mbed TLS Test mail\r\n"
  349. "To: %s\r\n"
  350. "MIME-Version: 1.0 (mime-construct 1.9)\n",
  351. "ESP32 SMTP Client", RECIPIENT_MAIL);
  352. /**
  353. * Note: We are not validating return for some ssl_writes.
  354. * If by chance, it's failed; at worst email will be incomplete!
  355. */
  356. ret = write_ssl_data(&ssl, (unsigned char *) buf, len);
  357. /* Multipart boundary */
  358. len = snprintf((char *) buf, BUF_SIZE,
  359. "Content-Type: multipart/mixed;boundary=XYZabcd1234\n"
  360. "--XYZabcd1234\n");
  361. ret = write_ssl_data(&ssl, (unsigned char *) buf, len);
  362. /* Text */
  363. len = snprintf((char *) buf, BUF_SIZE,
  364. "Content-Type: text/plain\n"
  365. "This is a simple test mail from the SMTP client example.\r\n"
  366. "\r\n"
  367. "Enjoy!\n\n--XYZabcd1234\n");
  368. ret = write_ssl_data(&ssl, (unsigned char *) buf, len);
  369. /* Attachment */
  370. len = snprintf((char *) buf, BUF_SIZE,
  371. "Content-Type: image/png;name=esp_logo.png\n"
  372. "Content-Transfer-Encoding: base64\n"
  373. "Content-Disposition:attachment;filename=\"esp_logo.png\"\r\n\n");
  374. ret = write_ssl_data(&ssl, (unsigned char *) buf, len);
  375. /* Image contents... */
  376. const uint8_t *offset = esp_logo_png_start;
  377. while (offset < esp_logo_png_end - 1) {
  378. int read_bytes = MIN(((sizeof (base64_buffer) - 1) / 4) * 3, esp_logo_png_end - offset - 1);
  379. ret = mbedtls_base64_encode((unsigned char *) base64_buffer, sizeof(base64_buffer),
  380. &base64_len, (unsigned char *) offset, read_bytes);
  381. if (ret != 0) {
  382. ESP_LOGE(TAG, "Error in mbedtls encode! ret = -0x%x", -ret);
  383. goto exit;
  384. }
  385. offset += read_bytes;
  386. len = snprintf((char *) buf, BUF_SIZE, "%s\r\n", base64_buffer);
  387. ret = write_ssl_data(&ssl, (unsigned char *) buf, len);
  388. }
  389. len = snprintf((char *) buf, BUF_SIZE, "\n--XYZabcd1234\n");
  390. ret = write_ssl_data(&ssl, (unsigned char *) buf, len);
  391. len = snprintf((char *) buf, BUF_SIZE, "\r\n.\r\n");
  392. ret = write_ssl_and_get_response(&ssl, (unsigned char *) buf, len);
  393. VALIDATE_MBEDTLS_RETURN(ret, 200, 299, exit);
  394. ESP_LOGI(TAG, "Email sent!");
  395. /* Close connection */
  396. mbedtls_ssl_close_notify(&ssl);
  397. ret = 0; /* No errors */
  398. exit:
  399. mbedtls_ssl_session_reset(&ssl);
  400. mbedtls_net_free(&server_fd);
  401. if (ret != 0) {
  402. mbedtls_strerror(ret, buf, 100);
  403. ESP_LOGE(TAG, "Last error was: -0x%x - %s", -ret, buf);
  404. }
  405. putchar('\n'); /* Just a new line */
  406. if (buf) {
  407. free(buf);
  408. }
  409. vTaskDelete(NULL);
  410. }
  411. void app_main(void)
  412. {
  413. ESP_ERROR_CHECK(nvs_flash_init());
  414. ESP_ERROR_CHECK(esp_netif_init());
  415. ESP_ERROR_CHECK(esp_event_loop_create_default());
  416. /**
  417. * This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
  418. * Read "Establishing Wi-Fi or Ethernet Connection" section in
  419. * examples/protocols/README.md for more information about this function.
  420. */
  421. ESP_ERROR_CHECK(example_connect());
  422. xTaskCreate(&smtp_client_task, "smtp_client_task", TASK_STACK_SIZE, NULL, 5, NULL);
  423. }