smtp_client_example_main.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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. memset(data, 0, DATA_SIZE);
  78. ret = mbedtls_net_recv(sock_fd, data, len);
  79. if (ret <= 0) {
  80. ESP_LOGE(TAG, "mbedtls_net_recv failed with error -0x%x", -ret);
  81. goto exit;
  82. }
  83. data[len] = '\0';
  84. printf("\n%s", data);
  85. len = ret;
  86. for (i = 0; i < len; i++) {
  87. if (data[i] != '\n') {
  88. if (idx < 4) {
  89. code[idx++] = data[i];
  90. }
  91. continue;
  92. }
  93. if (idx == 4 && code[0] >= '0' && code[0] <= '9' && code[3] == ' ') {
  94. code[3] = '\0';
  95. ret = atoi(code);
  96. goto exit;
  97. }
  98. idx = 0;
  99. }
  100. } while (1);
  101. exit:
  102. return ret;
  103. }
  104. static int write_ssl_and_get_response(mbedtls_ssl_context *ssl, unsigned char *buf, size_t len)
  105. {
  106. int ret;
  107. const size_t DATA_SIZE = 128;
  108. unsigned char data[DATA_SIZE];
  109. char code[4];
  110. size_t i, idx = 0;
  111. if (len) {
  112. ESP_LOGD(TAG, "%s", buf);
  113. }
  114. while (len && (ret = mbedtls_ssl_write(ssl, buf, len)) <= 0) {
  115. if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  116. ESP_LOGE(TAG, "mbedtls_ssl_write failed with error -0x%x", -ret);
  117. goto exit;
  118. }
  119. }
  120. do {
  121. len = DATA_SIZE - 1;
  122. memset(data, 0, DATA_SIZE);
  123. ret = mbedtls_ssl_read(ssl, data, len);
  124. if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  125. continue;
  126. }
  127. if (ret <= 0) {
  128. ESP_LOGE(TAG, "mbedtls_ssl_read failed with error -0x%x", -ret);
  129. goto exit;
  130. }
  131. ESP_LOGD(TAG, "%s", data);
  132. len = ret;
  133. for (i = 0; i < len; i++) {
  134. if (data[i] != '\n') {
  135. if (idx < 4) {
  136. code[idx++] = data[i];
  137. }
  138. continue;
  139. }
  140. if (idx == 4 && code[0] >= '0' && code[0] <= '9' && code[3] == ' ') {
  141. code[3] = '\0';
  142. ret = atoi(code);
  143. goto exit;
  144. }
  145. idx = 0;
  146. }
  147. } while (1);
  148. exit:
  149. return ret;
  150. }
  151. static int write_ssl_data(mbedtls_ssl_context *ssl, unsigned char *buf, size_t len)
  152. {
  153. int ret;
  154. if (len) {
  155. ESP_LOGD(TAG, "%s", buf);
  156. }
  157. while (len && (ret = mbedtls_ssl_write(ssl, buf, len)) <= 0) {
  158. if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  159. ESP_LOGE(TAG, "mbedtls_ssl_write failed with error -0x%x", -ret);
  160. return ret;
  161. }
  162. }
  163. return 0;
  164. }
  165. static int perform_tls_handshake(mbedtls_ssl_context *ssl)
  166. {
  167. int ret = -1;
  168. uint32_t flags;
  169. char *buf = NULL;
  170. buf = (char *) calloc(1, BUF_SIZE);
  171. if (buf == NULL) {
  172. ESP_LOGE(TAG, "calloc failed for size %d", BUF_SIZE);
  173. goto exit;
  174. }
  175. ESP_LOGI(TAG, "Performing the SSL/TLS handshake...");
  176. fflush(stdout);
  177. while ((ret = mbedtls_ssl_handshake(ssl)) != 0) {
  178. if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  179. ESP_LOGE(TAG, "mbedtls_ssl_handshake returned -0x%x", -ret);
  180. goto exit;
  181. }
  182. }
  183. ESP_LOGI(TAG, "Verifying peer X.509 certificate...");
  184. if ((flags = mbedtls_ssl_get_verify_result(ssl)) != 0) {
  185. /* In real life, we probably want to close connection if ret != 0 */
  186. ESP_LOGW(TAG, "Failed to verify peer certificate!");
  187. mbedtls_x509_crt_verify_info(buf, BUF_SIZE, " ! ", flags);
  188. ESP_LOGW(TAG, "verification info: %s", buf);
  189. } else {
  190. ESP_LOGI(TAG, "Certificate verified.");
  191. }
  192. ESP_LOGI(TAG, "Cipher suite is %s", mbedtls_ssl_get_ciphersuite(ssl));
  193. ret = 0; /* No error */
  194. exit:
  195. if (buf) {
  196. free(buf);
  197. }
  198. return ret;
  199. }
  200. static void smtp_client_task(void *pvParameters)
  201. {
  202. char *buf = NULL;
  203. unsigned char base64_buffer[128];
  204. int ret, len;
  205. size_t base64_len;
  206. mbedtls_entropy_context entropy;
  207. mbedtls_ctr_drbg_context ctr_drbg;
  208. mbedtls_ssl_context ssl;
  209. mbedtls_x509_crt cacert;
  210. mbedtls_ssl_config conf;
  211. mbedtls_net_context server_fd;
  212. mbedtls_ssl_init(&ssl);
  213. mbedtls_x509_crt_init(&cacert);
  214. mbedtls_ctr_drbg_init(&ctr_drbg);
  215. ESP_LOGI(TAG, "Seeding the random number generator");
  216. mbedtls_ssl_config_init(&conf);
  217. mbedtls_entropy_init(&entropy);
  218. if ((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
  219. NULL, 0)) != 0) {
  220. ESP_LOGE(TAG, "mbedtls_ctr_drbg_seed returned -0x%x", -ret);
  221. goto exit;
  222. }
  223. ESP_LOGI(TAG, "Loading the CA root certificate...");
  224. ret = mbedtls_x509_crt_parse(&cacert, server_root_cert_pem_start,
  225. server_root_cert_pem_end - server_root_cert_pem_start);
  226. if (ret < 0) {
  227. ESP_LOGE(TAG, "mbedtls_x509_crt_parse returned -0x%x", -ret);
  228. goto exit;
  229. }
  230. ESP_LOGI(TAG, "Setting hostname for TLS session...");
  231. /* Hostname set here should match CN in server certificate */
  232. if ((ret = mbedtls_ssl_set_hostname(&ssl, MAIL_SERVER)) != 0) {
  233. ESP_LOGE(TAG, "mbedtls_ssl_set_hostname returned -0x%x", -ret);
  234. goto exit;
  235. }
  236. ESP_LOGI(TAG, "Setting up the SSL/TLS structure...");
  237. if ((ret = mbedtls_ssl_config_defaults(&conf,
  238. MBEDTLS_SSL_IS_CLIENT,
  239. MBEDTLS_SSL_TRANSPORT_STREAM,
  240. MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
  241. ESP_LOGE(TAG, "mbedtls_ssl_config_defaults returned -0x%x", -ret);
  242. goto exit;
  243. }
  244. mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  245. mbedtls_ssl_conf_ca_chain(&conf, &cacert, NULL);
  246. mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg);
  247. #ifdef CONFIG_MBEDTLS_DEBUG
  248. mbedtls_esp_enable_debug_log(&conf, 4);
  249. #endif
  250. if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0) {
  251. ESP_LOGE(TAG, "mbedtls_ssl_setup returned -0x%x", -ret);
  252. goto exit;
  253. }
  254. mbedtls_net_init(&server_fd);
  255. ESP_LOGI(TAG, "Connecting to %s:%s...", MAIL_SERVER, MAIL_PORT);
  256. if ((ret = mbedtls_net_connect(&server_fd, MAIL_SERVER,
  257. MAIL_PORT, MBEDTLS_NET_PROTO_TCP)) != 0) {
  258. ESP_LOGE(TAG, "mbedtls_net_connect returned -0x%x", -ret);
  259. goto exit;
  260. }
  261. ESP_LOGI(TAG, "Connected.");
  262. mbedtls_ssl_set_bio(&ssl, &server_fd, mbedtls_net_send, mbedtls_net_recv, NULL);
  263. buf = (char *) calloc(1, BUF_SIZE);
  264. if (buf == NULL) {
  265. ESP_LOGE(TAG, "calloc failed for size %d", BUF_SIZE);
  266. goto exit;
  267. }
  268. #if SERVER_USES_STARTSSL
  269. /* Get response */
  270. ret = write_and_get_response(&server_fd, (unsigned char *) buf, 0);
  271. VALIDATE_MBEDTLS_RETURN(ret, 200, 299, exit);
  272. ESP_LOGI(TAG, "Writing EHLO to server...");
  273. len = snprintf((char *) buf, BUF_SIZE, "EHLO %s\r\n", "ESP32");
  274. ret = write_and_get_response(&server_fd, (unsigned char *) buf, len);
  275. VALIDATE_MBEDTLS_RETURN(ret, 200, 299, exit);
  276. ESP_LOGI(TAG, "Writing STARTTLS to server...");
  277. len = snprintf((char *) buf, BUF_SIZE, "STARTTLS\r\n");
  278. ret = write_and_get_response(&server_fd, (unsigned char *) buf, len);
  279. VALIDATE_MBEDTLS_RETURN(ret, 200, 299, exit);
  280. ret = perform_tls_handshake(&ssl);
  281. if (ret != 0) {
  282. goto exit;
  283. }
  284. #else /* SERVER_USES_STARTSSL */
  285. ret = perform_tls_handshake(&ssl);
  286. if (ret != 0) {
  287. goto exit;
  288. }
  289. /* Get response */
  290. ret = write_ssl_and_get_response(&ssl, (unsigned char *) buf, 0);
  291. VALIDATE_MBEDTLS_RETURN(ret, 200, 299, exit);
  292. ESP_LOGI(TAG, "Writing EHLO to server...");
  293. len = snprintf((char *) buf, BUF_SIZE, "EHLO %s\r\n", "ESP32");
  294. ret = write_ssl_and_get_response(&ssl, (unsigned char *) buf, len);
  295. VALIDATE_MBEDTLS_RETURN(ret, 200, 299, exit);
  296. #endif /* SERVER_USES_STARTSSL */
  297. /* Authentication */
  298. ESP_LOGI(TAG, "Authentication...");
  299. ESP_LOGI(TAG, "Write AUTH LOGIN");
  300. len = snprintf( (char *) buf, BUF_SIZE, "AUTH LOGIN\r\n" );
  301. ret = write_ssl_and_get_response(&ssl, (unsigned char *) buf, len);
  302. VALIDATE_MBEDTLS_RETURN(ret, 200, 399, exit);
  303. ESP_LOGI(TAG, "Write USER NAME");
  304. ret = mbedtls_base64_encode((unsigned char *) base64_buffer, sizeof(base64_buffer),
  305. &base64_len, (unsigned char *) SENDER_MAIL, strlen(SENDER_MAIL));
  306. if (ret != 0) {
  307. ESP_LOGE(TAG, "Error in mbedtls encode! ret = -0x%x", -ret);
  308. goto exit;
  309. }
  310. len = snprintf((char *) buf, BUF_SIZE, "%s\r\n", base64_buffer);
  311. ret = write_ssl_and_get_response(&ssl, (unsigned char *) buf, len);
  312. VALIDATE_MBEDTLS_RETURN(ret, 300, 399, exit);
  313. ESP_LOGI(TAG, "Write PASSWORD");
  314. ret = mbedtls_base64_encode((unsigned char *) base64_buffer, sizeof(base64_buffer),
  315. &base64_len, (unsigned char *) SENDER_PASSWORD, strlen(SENDER_PASSWORD));
  316. if (ret != 0) {
  317. ESP_LOGE(TAG, "Error in mbedtls encode! ret = -0x%x", -ret);
  318. goto exit;
  319. }
  320. len = snprintf((char *) buf, BUF_SIZE, "%s\r\n", base64_buffer);
  321. ret = write_ssl_and_get_response(&ssl, (unsigned char *) buf, len);
  322. VALIDATE_MBEDTLS_RETURN(ret, 200, 399, exit);
  323. /* Compose email */
  324. ESP_LOGI(TAG, "Write MAIL FROM");
  325. len = snprintf((char *) buf, BUF_SIZE, "MAIL FROM:<%s>\r\n", SENDER_MAIL);
  326. ret = write_ssl_and_get_response(&ssl, (unsigned char *) buf, len);
  327. VALIDATE_MBEDTLS_RETURN(ret, 200, 299, exit);
  328. ESP_LOGI(TAG, "Write RCPT");
  329. len = snprintf((char *) buf, BUF_SIZE, "RCPT TO:<%s>\r\n", RECIPIENT_MAIL);
  330. ret = write_ssl_and_get_response(&ssl, (unsigned char *) buf, len);
  331. VALIDATE_MBEDTLS_RETURN(ret, 200, 299, exit);
  332. ESP_LOGI(TAG, "Write DATA");
  333. len = snprintf((char *) buf, BUF_SIZE, "DATA\r\n");
  334. ret = write_ssl_and_get_response(&ssl, (unsigned char *) buf, len);
  335. VALIDATE_MBEDTLS_RETURN(ret, 300, 399, exit);
  336. ESP_LOGI(TAG, "Write Content");
  337. /* We do not take action if message sending is partly failed. */
  338. len = snprintf((char *) buf, BUF_SIZE,
  339. "From: %s\r\nSubject: mbed TLS Test mail\r\n"
  340. "To: %s\r\n"
  341. "MIME-Version: 1.0 (mime-construct 1.9)\n",
  342. "ESP32 SMTP Client", RECIPIENT_MAIL);
  343. /**
  344. * Note: We are not validating return for some ssl_writes.
  345. * If by chance, it's failed; at worst email will be incomplete!
  346. */
  347. ret = write_ssl_data(&ssl, (unsigned char *) buf, len);
  348. /* Multipart boundary */
  349. len = snprintf((char *) buf, BUF_SIZE,
  350. "Content-Type: multipart/mixed;boundary=XYZabcd1234\n"
  351. "--XYZabcd1234\n");
  352. ret = write_ssl_data(&ssl, (unsigned char *) buf, len);
  353. /* Text */
  354. len = snprintf((char *) buf, BUF_SIZE,
  355. "Content-Type: text/plain\n"
  356. "This is a simple test mail from the SMTP client example.\r\n"
  357. "\r\n"
  358. "Enjoy!\n\n--XYZabcd1234\n");
  359. ret = write_ssl_data(&ssl, (unsigned char *) buf, len);
  360. /* Attachment */
  361. len = snprintf((char *) buf, BUF_SIZE,
  362. "Content-Type: image/png;name=esp_logo.png\n"
  363. "Content-Transfer-Encoding: base64\n"
  364. "Content-Disposition:attachment;filename=\"esp_logo.png\"\r\n\n");
  365. ret = write_ssl_data(&ssl, (unsigned char *) buf, len);
  366. /* Image contents... */
  367. const uint8_t *offset = esp_logo_png_start;
  368. while (offset < esp_logo_png_end - 1) {
  369. int read_bytes = MIN(((sizeof (base64_buffer) - 1) / 4) * 3, esp_logo_png_end - offset - 1);
  370. ret = mbedtls_base64_encode((unsigned char *) base64_buffer, sizeof(base64_buffer),
  371. &base64_len, (unsigned char *) offset, read_bytes);
  372. if (ret != 0) {
  373. ESP_LOGE(TAG, "Error in mbedtls encode! ret = -0x%x", -ret);
  374. goto exit;
  375. }
  376. offset += read_bytes;
  377. len = snprintf((char *) buf, BUF_SIZE, "%s\r\n", base64_buffer);
  378. ret = write_ssl_data(&ssl, (unsigned char *) buf, len);
  379. }
  380. len = snprintf((char *) buf, BUF_SIZE, "\n--XYZabcd1234\n");
  381. ret = write_ssl_data(&ssl, (unsigned char *) buf, len);
  382. len = snprintf((char *) buf, BUF_SIZE, "\r\n.\r\n");
  383. ret = write_ssl_and_get_response(&ssl, (unsigned char *) buf, len);
  384. VALIDATE_MBEDTLS_RETURN(ret, 200, 299, exit);
  385. ESP_LOGI(TAG, "Email sent!");
  386. /* Close connection */
  387. mbedtls_ssl_close_notify(&ssl);
  388. ret = 0; /* No errors */
  389. exit:
  390. mbedtls_net_free(&server_fd);
  391. mbedtls_x509_crt_free(&cacert);
  392. mbedtls_ssl_free(&ssl);
  393. mbedtls_ssl_config_free(&conf);
  394. mbedtls_ctr_drbg_free(&ctr_drbg);
  395. mbedtls_entropy_free(&entropy);
  396. if (ret != 0) {
  397. mbedtls_strerror(ret, buf, 100);
  398. ESP_LOGE(TAG, "Last error was: -0x%x - %s", -ret, buf);
  399. }
  400. putchar('\n'); /* Just a new line */
  401. if (buf) {
  402. free(buf);
  403. }
  404. vTaskDelete(NULL);
  405. }
  406. void app_main(void)
  407. {
  408. ESP_ERROR_CHECK(nvs_flash_init());
  409. ESP_ERROR_CHECK(esp_netif_init());
  410. ESP_ERROR_CHECK(esp_event_loop_create_default());
  411. /**
  412. * This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
  413. * Read "Establishing Wi-Fi or Ethernet Connection" section in
  414. * examples/protocols/README.md for more information about this function.
  415. */
  416. ESP_ERROR_CHECK(example_connect());
  417. xTaskCreate(&smtp_client_task, "smtp_client_task", TASK_STACK_SIZE, NULL, 5, NULL);
  418. }