smtp_client_example_main.c 16 KB

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