概要
Googleのメールサーバーを使ってESP32からメールを送る方法について説明します。
アプリ パスワードの取得
メールを送る為には ”アプリ パスワード” が必要です。取得方法は以下の通り。
- Google アカウントにアクセスし、ログイン。
- 左側のメニューから "セキュリティ" をクリック。
- "2段階認証プロセス"をオン。
- 設定完了後、"セキュリティ"画面の"アプリ パスワード"をクリック。
- アプリとデバイスの名前(例:"ESP32-maile"など)を選択し、"生成" をクリック。
- 画面に表示された16桁のパスコードがアプリ パスワードです。
4番が見つからない事が有ります。その時は、https://myaccount.google.com/ にアクセスし検索窓に ”アプリ パスワード” と入力して下さい。そこから入れます。
メール送信サンプルコード
send_mail.ino
arduino
#include "Arduino.h"
#include "LittleFS.h"
#include <WiFi.h>
#include "FS.h"
#include <ESP_Mail_Client.h>
#include "esp_sntp.h"
#include "time.h"
// --- Wi-Fi設定(ご自身の環境に書き換えてください) ---
#define SSID "YOUR_WIFI_SSID"
#define PASSWORD "YOUR_WIFI_PASSWORD"
// --- Gmail設定 ---
#define SMTP_HOST "smtp.gmail.com"
#define SMTP_PORT 465
/* The sign in credentials */
#define AUTHOR_EMAIL "xxxxx@gmail.com"
#define AUTHOR_PASSWORD "yyyyyyyyyyyyyyyy"
/* Recipient's email*/
String recipient_email = "abcefg@yahoo.co.jp";
void setup() {
Serial.begin(115200);
// LittleFSの初期化
if(!LittleFS.begin(true)){ // trueを入れるとフォーマット失敗時に自動フォーマット
Serial.println("LittleFS Mount Failed");
return;
}
// WiFi接続
WiFi.disconnect(true);
WiFi.mode(WIFI_STA);
WiFi.begin(SSID, PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWi-Fi Connected!");
// NTPでの時刻同期設定(日本のタイムゾーン UTC+9)
configTzTime("JST-9", "ntp.nict.jp", "time.google.com", "pool.ntp.org");
Serial.print("Waiting for program time to be set...");
// 時刻が正しく取得できるまで待つ
time_t now = time(nullptr);
while (now < 24 * 3600) {
const int retry_delay_ms = 500;
delay(retry_delay_ms);
Serial.print(".");
now = time(nullptr);
}
Serial.println("\nTime is set!");
// メール送信
send_mail("/samp.jpg");
}
void send_mail(String _fileName){
//セッション設定(接続・ログイン情報)
Session_Config config;
config.server.host_name = SMTP_HOST;
config.server.port = SMTP_PORT;
config.login.email = AUTHOR_EMAIL;
config.login.password = AUTHOR_PASSWORD;
//メッセージ設定(差出人、宛先、件名、本文)
SMTP_Message message;
message.sender.name = "ESP32";
message.sender.email = AUTHOR_EMAIL;
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_normal; // 優先度(Normal)
message.subject = "画像を送ります" + _fileName;
// 本文
message.text.content = "Send Mail.";
// 宛先の追加(表示名, メールアドレス)
message.addRecipient("", recipient_email.c_str());
SMTP_Attachment att;
att.descr.filename = _fileName; // 受信側で見えるファイル名
String fullPath = _fileName;
att.file.path = fullPath; // file.path
att.file.storage_type = esp_mail_file_storage_type_flash;
att.descr.mime = "image/jpeg"; // ファイルのMIMEタイプ(jpeg画像)
// メッセージに添付ファイルを追加
message.addAttachment(att);
// 送信の実行
SMTPSession smtp;
smtp.callback(sendCallback); // コールバックの登録
// サーバーに接続
if (!smtp.connect(&config)) {
Serial.printf("Connection error, Status Code: %d, Error Code: %d, Reason: %s\n", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str());
return;
}
// メールを送信
if (!MailClient.sendMail(&smtp, &message)) {
Serial.println("Error sending Email, " + smtp.errorReason());
}
}
void loop() {
delay(50);
}
void sendCallback(SMTP_Status status) {
Serial.println(status.info());
if (status.success()) {
Serial.println("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.printf("Message sent fail: %d\n", status.failedCount());
Serial.println("----------------");
}
}
- 10,11行:ルータの "SSID" と "PASSWORD" を入力。
- 14,15行:SMTP_HOSTのIPアドレスとポート。
- 18行:自分のGmailアドレス。
- 19行:アプリパスワード。16桁のGoogleから入手したもの。
- 22行:送信先メールアドレス
- WiFiに接続し、時間を合わせます。
- 送信元(今回はESP32)の時間が不適切だとSMTPがエラーを返します。
- メール送信前にNTPから時間を取得しセットします。
- send_mail("/samp.jpg");がメールを送信する関数
- 63~67行:ログイン情報の設定
- 70~80行:差出人、宛先、件名、本文の設定
- 82~90行:添付ファイルの設定
- 今回はLittleFSのルートに保存した "/samp.jpg" という画像データを添付します。
- 86行:LittleFSの場合、att.file.storage_type = esp_mail_file_storage_type_flash; と設定する。
- 87行:内容に合わせてMIMEを設定し送信する。
- 94行:送信の状況をこの関数が表示します。
コンパイル実行するとシリアルモニタに下記を表示。宛先にメールが送信されます。
#### Connecting to SMTP server...
#### SMTP server connected
#### Sending greeting response...
#### Logging in...
#### Sending Email...
#### Sending message header...
#### Sending message body...
#### Sending attachments...
#### /samp.jpg
> C: [ ] 0 %
> C: [# ] 10 %
> C: [## ] 15 %
> C: [### ] 20 %
> C: [#### ] 25 %
> C: [##### ] 35 %
> C: [###### ] 40 %
> C: [####### ] 45 %
> C: [######## ] 50 %
> C: [######### ] 60 %
> C: [########## ] 65 %
> C: [########### ] 70 %
> C: [############ ] 75 %
> C: [############# ] 85 %
> C: [############## ] 90 %
> C: [############### ] 95 %
> C: [################] 100 %
#### Finishing the message sending...
#### Closing the session...
#### Message sent successfully
----------------
Message sent success: 1
Message sent fail: 0
----------------
最後に
アプリ パスワード(AUTHOR_PASSWORD)の取得でちょっと戸惑ったのですが、それ以外は問題無く実行出来ました。 これで自作機からメールを送る事が出来る様になりました。