본문 바로가기

ESP32

ESP32를 사용하여 SMTP 서버를 통해 이메일 보내기

반응형

ESP32를 사용하여 SMTP 서버를 통해 이메일 보내기 (Arduino IDE)

 

ESP32를 사용하여 SMTP 서버를 통해 이메일을 보내는 방법을 알아보세요 . 간단한 HTML 또는 일반 텍스트 이메일을 보내는 방법은 물론 이미지나 파일( .txt ) 과 같은 첨부 파일을 보내는 방법도 보여드리겠습니다 . 아두이노 IDE를 사용하여 ESP32 보드를 프로그래밍합니다.

 

이 튜토리얼에서는 다음 주제를 다룹니다.

  • ESP32를 이용한 이메일 전송 (HTML 및 일반 텍스트)
  • ESP32를 이용해 이미지 및 텍스트 파일 첨부 이메일을 보내는 방법

 

 

SMTP 서버 소개

 

SMTP는 Simple Mail Transfer Protocol 의 약자 로 , 이메일 전송 을 위한 인터넷 표준입니다. ESP32 를 SMTP 서버에 연결해야 이메일을 보낼 수 있습니다.

 

ESP 메일 클라이언트 라이브러리

 

ESP32 에서 이메일을 보내기 위해 ESP-Mail-Client 라이브러리를 사용하겠습니다 . 이 라이브러리를 사용하면 ESP32 는 SMTP 및 IMAP 서버를 통해 첨부 파일이 있거나 없는 이메일을 주고받을 수 있습니다.

 

이 튜토리얼에서는 SMTP를 사용하여 첨부 파일이 있거나 없는 이메일을 보내는 방법을 설명합니다. 예시로 이미지 파일(.png)과 텍스트 파일(.txt)을 보내 보겠습니다. 이메일 파일은 ESP32 파일 시스템(SPIFFS) 또는 microSD 카드에 저장할 수 있습니다(단, 이 튜토리얼에서는 microSD 카드 사용법을 다루지 않습니다).

 

ESP-Mail-Client 라이브러리 설치

 

이 튜토리얼을 진행하기 전에 ESP-Mail-Client 라이브러리를 설치해야 합니다 . 이 라이브러리는 Arduino IDE 라이브러리 관리자를 사용하여 설치할 수 없습니다 . 라이브러리를 설치하려면 다음 단계를 따르세요.

 

  1. ESP 메일 클라이언트 라이브러리 .zip 폴더를 다운로드하려면 여기를 클릭하십시오.
  2. 아두이노 IDE 에서 스케치 > 라이브러리 포함 > .ZIP 라이브러리 추가로 이동합니다.
  3. 방금 다운로드한 .zip 파일을 선택하세요 .

 

그런 다음, 파일 > 예제 > ESP-Mail-Client 에서 다양한 예제를 시도해 볼 수 있습니다. 예제는 라이브러리의 GitHub 페이지 에서도 확인할 수 있습니다 .

 

라이브러리를 포함시키려면 VS Code와 PlatformIO를 사용하여 ESP32를 사용하는 경우 다음 내용을 platformio.ini 파일에 복사하세요 .

 

lib_deps = mobizt/ESP Mail Client @ ^1.3.0

 

발신자 이메일 (신규 계정)

 

개인 이메일 주소로 이메일을 보내려면 새 이메일 계정을 만드는 것이 좋습니다. ESP32를 사용하여 개인 이메일 주소로 이메일을 보내지 마십시오 . 코드에 오류가 발생하거나 실수로 과도한 요청을 보내는 경우 계정이 차단되거나 일시적으로 정지될 수 있습니다.

 

이메일을 보내기 위해 새로 만든 Gmail.com 계정을 사용하겠지만, 다른 이메일 서비스를 사용하셔도 괜찮습니다. 수신자의 이메일 주소는 귀하의 이메일 주소여도 전혀 문제가 없습니다.

 

발신자 이메일 계정 생성

 

ESP32 를 사용하여 이메일을 보내려면 새 이메일 계정을 만들어야 합니다. Gmail 계정을 사용하려면 이 링크를 클릭하세요.

 

Gmail 새 계정 만들기

 

앱 비밀번호 생성하기

 

ESP32가 Gmail 계정을 사용하여 이메일을 보내 려면 앱 암호를 생성해야 합니다 . 보안 수준이 낮은 앱이나 기기는 16자리 암호를 사용하여 Google 계정에 액세스할 수 있는 권한을 부여받습니다. 앱 암호를 사용한 로그인에 대한 자세한 내용은 여기를 참조하세요 .

 

앱 비밀번호는 2단계 인증이 활성화된 계정에서만 사용할 수 있습니다 .

  1. Google 계정을 여세요 .
  2. 탐색 패널에서 " 보안 "을 선택합니다.
  3. "Google에 로그인"에서 2단계 인증 > 시작하기를 선택하세요 .
  4. 화면에 나오는 단계를 따르세요.

 

2단계 인증을 활성화한 후 앱 비밀번호를 생성할 수 있습니다.

 

  1. Google 계정을 여세요 .
  2. 탐색 패널에서 보안을 선택합니다 .
  3. “Google에 로그인”에서 “앱 암호”를 선택하세요 .

Gmail 앱 비밀번호 생성

 

'앱 선택' 필드에서 '메일'을 선택하세요. 장치 이름을 ESP32 와 같이 지정하고 '기타'를 선택합니다. 그런 다음 '생성' 버튼을 클릭합니다. ESP32 또는 ESP8266을 사용하여 이메일을 보내면 암호를 입력하는 창이 나타납니다. 암호를 기억할 필요가 없다고 표시되더라도 나중에 필요합니다.

 

생성된 앱 비밀번호 Gmail

 

이제 ESP32 코드 에서 이메일을 보낼 때 사용할 앱 비밀번호를 갖게 되었습니다 .

 

ESP32에서 이메일을 보내기 위해 Gmail 앱 비밀번호를 생성했습니다.

 

다른 이메일 제공업체를 사용하는 경우 앱 암호를 만드는 방법을 확인하세요. 구글에서 "이메일 제공업체 이름 + 앱 암호 만들기"를 검색하면 관련 안내를 찾을 수 있습니다.

 

Gmail SMTP 서버 설정

 

Gmail 계정을 사용하시는 경우 SMTP 서버 정보는 다음과 같습니다.

SMTP 서버: smtp.gmail.com

SMTP 사용자 이름: 전체 Gmail 주소

SMTP 비밀번호: Gmail 비밀번호

SMTP 포트(TLS): 587

SMTP 포트(SSL): 465

SMTP TLS/SSL 필수: 예

 

Outlook SMTP 서버 설정

 

Outlook 계정의 경우 SMTP 서버 설정은 다음과 같습니다.

SMTP 서버: smtp.office365.com

SMTP 사용자 이름: 전체 Outlook 이메일 주소

SMTP 비밀번호: Outlook 비밀번호

SMTP 포트: 587

SMTP TLS/SSL 필수: 예

 

Live 또는 Hotmail SMTP 서버 설정

 

Live 또는 Hotmail 계정의 경우 SMTP 서버 설정은 다음과 같습니다.

SMTP 서버: smtp.live.com

SMTP 사용자 이름: Live/Hotmail 이메일 주소 전체

SMTP 비밀번호: Windows Live Hotmail 비밀번호

SMTP 포트: 587

SMTP TLS/SSL 필수: 예

 

다른 이메일 서비스를 사용하는 경우 해당 서비스의 SMTP 서버 설정을 찾아야 합니다. 이제 ESP32 에서 이메일을 보내는 데 필요한 모든 것을 갖추었습니다 .

 

ESP32(Arduino IDE)를 사용하여 HTML 또는 일반 텍스트로 이메일을 보내는 방법

 

다음 코드는 SMTP 서버를 통해 HTML 또는 일반 텍스트를 포함한 이메일을 전송합니다. ESP32 는 데모 목적으로 부팅 시 한 번 이메일을 전송합니다. 이후에는 코드를 수정하여 프로젝트에 통합할 수 있습니다.

 

아직 코드를 업로드하지 마세요. 제대로 작동하려면 몇 가지 수정이 필요합니다.

 

/*
  BokFive
  Complete project details at:
   - ESP32: https://ebokify.com/send-email-from-esp32-via-smtp-server/
   - ESP8266: https://ebokify.com/send-email-from-esp8266-nodemcu-via-smtp-server/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  Example adapted from: https://github.com/mobizt/ESP-Mail-Client
*/

// To send Emails using Gmail on port 465 (SSL), you need to create an app password: https://support.google.com/accounts/answer/185833

#include <Arduino.h>
#if defined(ESP32)
  #include <WiFi.h>
#elif defined(ESP8266)
  #include <ESP8266WiFi.h>
#endif
#include <ESP_Mail_Client.h>

#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

#define SMTP_HOST "smtp.gmail.com"
#define SMTP_PORT 465

/* The sign in credentials */
#define AUTHOR_EMAIL "YOUR_EMAIL@XXXX.com"
#define AUTHOR_PASSWORD "YOUR_EMAIL_PASS"

/* Recipient's email*/
#define RECIPIENT_EMAIL "RECIPIENTE_EMAIL@XXXX.com"

/* 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);
  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
  */
  smtp.debug(1);

  /* Set the callback function to get the sending results */
  smtp.callback(smtpCallback);

  /* Declare the session config data */
  ESP_Mail_Session session;

  /* 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 = "";

  /* Declare the message class */
  SMTP_Message message;

  /* Set the message headers */
  message.sender.name = "ESP";
  message.sender.email = AUTHOR_EMAIL;
  message.subject = "ESP Test Email";
  message.addRecipient("Sara", RECIPIENT_EMAIL);

  /*Send HTML message*/
  String htmlMsg = "<div style=\"color:#2f4468;\"><h1>Hello World!</h1><p>- Sent from ESP board</p></div>";
  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;

  /*
  //Send raw text message
  String textMsg = "Hello World! - Sent from ESP board";
  message.text.content = textMsg.c_str();
  message.text.charSet = "us-ascii";
  message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
  
  message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
  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());
}

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.c_str());
      ESP_MAIL_PRINTF("Subject: %s\n", result.subject.c_str());
    }
    Serial.println("----------------\n");
  }
}

 

발신자 이메일, SMTP 서버 정보, 수신자 및 메시지를 입력하는 것 외에도 네트워크 자격 증명을 설정해야 합니다.

 

코드 작동 방식

 

이 코드는 라이브러리 예제를 수정한 것입니다. 예제 코드에는 주석이 잘 달려 있어 각 줄의 기능을 쉽게 이해할 수 있습니다. 이제 여러분이 수정해야 하거나 수정할 가능성이 있는 관련 부분을 살펴보겠습니다.

 

먼저 다음 줄에 네트워크 자격 증명을 입력하십시오.

 

#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"

#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

 

SMTP 서버 설정에 해당 주소를 입력하세요. Gmail 계정을 사용하여 이메일을 보내는 경우 설정은 다음과 같습니다.

 

#define SMTP_HOST "smtp.gmail.com"

#define SMTP_PORT 465

 

발신자 이메일 로그인 자격 증명을 입력하세요(이전에 생성한 이메일 주소와 앱 비밀번호를 입력하세요).

 

#define AUTHOR_EMAIL "YOUR_EMAIL@XXXX.com"

#define AUTHOR_PASSWORD "YOUR_EMAIL_PASS"

 

수신자 이메일을 입력하세요:

 

#define RECIPIENT_EMAIL "RECIPIENTE_EMAIL@XXXX.com"

 

메시지 헤더를 설정 setup()하려면 다음 줄을 포함시키세요. 발신자 이름, 발신자 이메일, 이메일 주제, 수신자 이름 및 이메일.

 

/* Set the message headers */

message.sender.name = "ESP";

message.sender.email = AUTHOR_EMAIL;

message.subject = "ESP Test Email";

message.addRecipient("Sara", RECIPIENT_EMAIL);

 

textMsg다음 줄에서 메시지 내용(원본 텍스트)을 변수에 설정하십시오 .

 

//Send raw text message

String textMsg = "Hello World - Sent from ESP board";

message.text.content = textMsg.c_str();

message.text.charSet = "us-ascii";

message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;

 

HTML 텍스트를 보내려면 다음 줄의 주석 처리를 해제하고 해당 htmlMsg 변수에 HTML 텍스트를 삽입하세요.

 

/*Send HTML message*/
/*String htmlMsg = "<div style=\"color:#2f4468;\"><h1>Hello World!</h1><p>- Sent from ESP board</p></div>";
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;*/

 

 

마지막으로, 다음 줄들이 메시지를 전송합니다:

 

if (!MailClient.sendMail(&smtp, &message))

  Serial.println("Error sending Email, " + smtp.errorReason());

 

데모

 

ESP32 에 코드를 업로드하세요. 업로드가 완료되면 115200bps의 전송 속도로 시리얼 모니터를 여세요. 버튼을 눌러 ESP32 를 리셋하세요.

 

모든 것이 계획대로 진행되었다면 시리얼 모니터에 다음과 유사한 메시지가 표시될 것입니다.

 

ESP 이메일 메시지 전송 성공 (시리얼 모니터)

 

이메일 계정을 확인하세요. ESP32 보드 에서 보낸 이메일을 받으셨을 겁니다 .

 

ESP32 SMTP 서버 이메일 수신 테스트

 

HTML 텍스트로 메시지를 보내도록 설정하면 메시지는 다음과 같이 표시됩니다.

 

ESP32 SMTP 서버를 사용하여 본문 텍스트가 HTML 형식인 이메일을 전송합니다.

 

텍스트 메시지 수신을 활성화했다면 다음과 같은 이메일을 받게 될 것입니다.

 

ESP32 SMTP 서버를 사용하여 본문 텍스트만 포함된 이메일을 전송하는 방법

 

ESP32를 사용하여 이메일로 첨부 파일 보내기 (Arduino IDE)

 

이 부분에서는 ESP32 를 사용하여 이메일에 첨부 파일을 보내는 방법을 보여드리겠습니다 . .txt 형식의 그림이나 파일을 보내는 방법을 설명할 것입니다 . 이 기능은 지난 몇 시간 동안의 센서 측정값이 담긴 .txt 파일이나 ESP32 -CAM으로 촬영한 사진을 보내는 데 유용합니다 .

 

이 튜토리얼을 위해 전송할 파일은 ESP32 파일 시스템(SPIFFS)에 저장되어 있어야 합니다.

 

SPIFFS에 파일을 업로드하세요

 

이메일로 파일을 전송하기 전에 ESP32 파일 시스템(SPIFFS) 에 저장해야 합니다 . 아두이노 IDE 용 ESP32 Filesystem Uploader 플러그인을 사용하여 사진과 .txt 파일을 ESP32 SPIFFS에 업로드해 보겠습니다. 아직 플러그인을 설치하지 않았다면 다음 튜토리얼에서 설치하세요.

 

아두이노 IDE에 ESP32 SPIFFS 파일 시스템 업로더를 설치하세요

 

새로운 아두이노 스케치를 생성하고 저장합니다. [스케치] > [스케치 폴더 표시 ]를 선택합니다. 아두이노 스케치 폴더 안에 " data " 라는 폴더를 생성합니다 . a.jpg 파일과 a.txt 파일을 data 폴더에 추가합니다.

 

또는 여기를 클릭하여 프로젝트 폴더를 다운로드할 수도 있습니다 .

 

기본 코드에 따라 파일 이름은 image.png 와 text_file.txt 여야 합니다 . 다른 이름의 파일을 가져오도록 코드를 수정할 수도 있습니다.

 

저희는 다음 파일들을 보내드리겠습니다 :

 

ESP32 ESP8266 텍스트 파일 및 이미지 첨부 파일을 포함한 이메일 전송

 

폴더 구조는 다음과 같아야 합니다( 프로젝트 폴더 다운로드 ):

 

이메일 첨부파일 보내기, 폴더 구조, 파일 시스템, 파일 정리

 

아두이노 IDE 에서 [도구] > [ESP32 스케치 데이터 업로드] 로 이동 한 후 파일을 데이터 폴더 로 옮기고 파일 업로드가 완료될 때까지 기다리세요 .

 

ESP32 스케치 데이터 업로드 아두이노 IDE SPIFFS 파일 시스템

 

디버깅 창에 성공 메시지가 표시될 것입니다. 파일 업로드가 성공적으로 완료되면 다음 단계로 진행하세요.

 

SPIFFS 이미지 업로드 완료 성공 메시지

 

메모:디버깅 창에 많은 점들이 표시되기 시작하면 , 파일 업로드를 위해 ESP32 보드의 BOOT 버튼을 길게 눌러야 합니다 .

 

코드

 

다음 코드는 텍스트 파일과 이미지를 첨부하여 이메일을 보냅니다. 코드를 업로드하기 전에 발신자 이메일 주소와 수신자 이메일 주소를 입력했는지 확인하세요.

 

/*
  BokFive
  Complete project details at:
   - ESP32: https://ebokify.com/send-email-from-esp32-via-smtp-server/
   
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  Example adapted K. Suwatchai (Mobizt): https://github.com/mobizt/ESP-Mail-Client Copyright (c) 2021 mobizt
*/

// To send Emails using Gmail on port 465 (SSL), you need to create an app password: https://support.google.com/accounts/answer/185833
// The file systems for flash and sd memory can be changed in ESP_Mail_FS.h.

#include <Arduino.h>
#if defined(ESP32)
  #include <WiFi.h>
#elif defined(ESP8266)
  #include <ESP8266WiFi.h>
#endif
#include <ESP_Mail_Client.h>

#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

#define SMTP_HOST "smtp.gmail.com"

/** 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 465

/* The log in credentials */
#define AUTHOR_EMAIL "YOUR_EMAIL@XXXX.com"
#define AUTHOR_PASSWORD "YOUR_EMAIL_PASS"

/* Recipient's email*/
#define RECIPIENT_EMAIL "RECIPIENTE_EMAIL@XXXX.com"
/* 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);
  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();

  if (!SPIFFS.begin(true)) {
    Serial.println("An error has occurred while mounting SPIFFS");
  }
  else{
    Serial.println("SPIFFS mounted successfully");
  }

  /** Enable the debug via Serial port
   * none debug or 0
   * basic debug or 1
  */
  smtp.debug(1);

  /* Set the callback function to get the sending results */
  smtp.callback(smtpCallback);

  /* Declare the session config data */
  ESP_Mail_Session session;

  /* 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;

  /* Enable the chunked data transfer with pipelining for large message if server supported */
  message.enable.chunking = true;

  /* Set the message headers */
  message.sender.name = "ESP Mail";
  message.sender.email = AUTHOR_EMAIL;

  message.subject = "Test sending Email with attachments and inline images from SD card and Flash";
  message.addRecipient("Sara", RECIPIENT_EMAIL);

  /** Two alternative content versions are sending in this example e.g. plain text and html */
  String htmlMsg = "This message contains attachments: image and text file.";
  message.html.content = htmlMsg.c_str();
  message.html.charSet = "utf-8";
  message.html.transfer_encoding = Content_Transfer_Encoding::enc_qp;

  message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_normal;
  message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay;

  /* The attachment data item */
  SMTP_Attachment att;

  /** Set the attachment info e.g. 
   * file name, MIME type, file path, file storage type,
   * transfer encoding and content encoding
  */
  att.descr.filename = "image.png";
  att.descr.mime = "image/png"; //binary data
  att.file.path = "/image.png";
  att.file.storage_type = esp_mail_file_storage_type_flash;
  att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;

  /* Add attachment to the message */
  message.addAttachment(att);

  message.resetAttachItem(att);
  att.descr.filename = "text_file.txt";
  att.descr.mime = "text/plain";
  att.file.path = "/text_file.txt";
  att.file.storage_type = esp_mail_file_storage_type_flash;
  att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;

  /* Add attachment to the message */
  message.addAttachment(att);

  /* Connect to server with the session config */
  if (!smtp.connect(&session))
    return;

  /* Start sending the Email and close the session */
  if (!MailClient.sendMail(&smtp, &message, true))
    Serial.println("Error sending Email, " + smtp.errorReason());
}

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.c_str());
      ESP_MAIL_PRINTF("Subject: %s\n", result.subject.c_str());
    }
    Serial.println("----------------\n");
  }
}

 

코드 작동 방식

 

이 코드는 이전 코드와 매우 유사하므로 첨부 파일을 보내는 데 필요한 부분만 살펴보겠습니다.

 

setup() 함수에서 SPIFFS를 초기화해야 합니다.

 

if(!SPIFFS.begin(true)) {

Serial.println("An Error has occurred while mounting SPIFFS");

return;

}

 

다음과 같이 첨부 파일을 생성해야 합니다.

 

/* The attachment data item */

SMTP_Attachment att;

 

다음으로 첨부 파일 정보(파일 이름, MIME 유형, 파일 경로, 파일 저장 유형 및 전송 인코딩)를 추가합니다. 다음 줄에서 이미지 파일을 전송합니다.

 

att.descr.filename = "image.png";

att.descr.mime = "image/png";

att.file.path = "/image.png";

att.file.storage_type = esp_mail_file_storage_type_flash;

att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;

 

마지막으로 메시지에 첨부 파일을 추가하세요.

 

message.addAttachment(att);

 

첨부 파일을 더 보내려면 다음 첨부 파일을 추가하기 전에 다음 줄을 호출해야 합니다.

 

message.resetAttachItem(att);

 

다음으로, 다른 첨부 파일(텍스트 파일)의 세부 정보를 입력하십시오.

 

att.descr.filename = "text_file.txt";

att.descr.mime = "text/plain";

att.file.path = "/text_file.txt";

att.file.storage_type = esp_mail_file_storage_type_flash;

att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;

 

그리고 이 첨부 파일을 메시지에 추가하세요:

 

message.addAttachment(att);

 

마지막으로, 이전 예시에서와 마찬가지로 메시지를 보내기만 하면 됩니다.

 

if (!MailClient.sendMail(&smtp, &message, true))

Serial.println("Error sending Email, " + smtp.errorReason());

 

데모

 

코드를 업로드한 후, 시리얼 모니터를 115200bps 속도로 열고 보드에 내장된 EN/RESET 버튼을 누르십시오. 모든 것이 정상적으로 진행되면 시리얼 모니터에 다음과 유사한 메시지가 표시될 것입니다.

 

ESP 이메일 메시지 전송 성공 (시리얼 모니터)

 

수신자의 이메일 주소를 확인하세요. 첨부 파일 두 개가 포함된 새 이메일을 받으셨을 겁니다.

 

ESP32 및 ESP8266을 사용하여 첨부 파일이 있는 이메일 보내기

 

결론

 

이 튜토리얼에서는 ESP32 를 사용하여 SMTP 서버 로 이메일을 보내는 방법을 배웠습니다 . 이 방법을 사용하려면 ESP32가 인터넷에 연결되어 있어야 합니다.

 

SMTP 서버를 사용하고 싶지 않다면 ESP32 또는 ESP8266 보드를 이용해 이메일 알림을 보내는 PHP 스크립트를 작성할 수 있습니다.

 

본문과 첨부파일을 포함한 간단한 이메일을 보내는 방법을 배웠습니다. 확장 프로그램을 사용할 경우, 해당 파일은 ESP32 파일 시스템(SPIFFS) 또는 microSD 카드 (이 튜토리얼에서는 다루지 않음)에 저장해야 합니다.

 

이 예제들은 ESP32 부팅 시 이메일을 한 통 보내는 방법을 보여줍니다 . 이 코드를 수정하여 여러분의 프로젝트에 활용하는 것이 좋습니다. 예를 들어, 센서 측정값이 담긴 .txt 파일을 보내거나, ESP32 -CAM으로 촬영한 사진을 보내거나, 딥 슬립 모드를 사용하여 매시간 보드를 깨우거나, 데이터를 담은 이메일을 보내는 등 다양한 용도로 활용할 수 있습니다.

 

위 튜토리얼의 원문 참고 사이트를 링크로 연결합니다. 원문 저자에게 감사합니다.

 

 

반응형

캐어랩 고객 지원

취업, 창업의 막막함, 외주 관리, 제품 부재!

당신의 고민은 무엇입니까? 현실과 동떨어진 교육, 실패만 반복하는 외주 계약, 아이디어는 있지만 구현할 기술이 없는 막막함.

우리는 알고 있습니다. 문제의 원인은 '명확한 학습, 실전 경험과 신뢰할 수 있는 기술력의 부재'에서 시작됩니다.

이제 고민을 멈추고, 캐어랩을 만나세요!

코딩(펌웨어), 전자부품과 디지털 회로설계, PCB 설계 제작, 고객(시장/수출) 발굴과 마케팅 전략으로 당신을 지원합니다.

제품 설계의 고수는 성공이 만든 게 아니라 실패가 만듭니다. 아이디어를 양산 가능한 제품으로!

귀사의 제품을 만드세요. 교육과 개발 실적으로 신뢰할 수 있는 파트너를 확보하세요.

지난 30년 여정, 캐어랩이 얻은 모든 것을 함께 나누고 싶습니다.

카카오 채널 추가하기

카톡 채팅방에서 무엇이든 물어보세요

당신의 성공을 위해 캐어랩과 함께 하세요.

캐어랩 온라인 채널 바로가기

캐어랩