Arduinoからメールを送信する

SMTPClientライブラリを使う


前回、Arduino Playgroundのサンプルコードを使ってメール送信を紹介しました。
そこで、今回はSMTPClientライブラリを使ったメール送信を紹介します。
使用したシールドは前回と同じW5100モジュールです。

こちらにオリジナルの SMTPClientライブラリがありますが、ソースを確認したところ、
SMTP2GOの認証手順に対応していなかったので、SMTP2GOでメールが送れるように改造してみました。
かなり手を入れたので、一式こちらか らダウンロードできるようにしておきます。
ダウンロードして展開したらそのままライブラリフォルダーに移動してください。

以下の値は変更が必要です。
user64:こちらのページで紹介しました「Email AddressをBase64に変換した文字列」
pass64:こちらのページで紹介しました「PasswordをBase64に変換し た文 字列」
mail_from:メール送信者のメールアドレス
mail_to:メール送信先のメールアドレス(Toアドレス)
mail_cc:メール送信先のメールアドレス(Ccアドレス)
mail_bcc:メール送信先のメールアドレス(Bccアドレス)

スケッチを見て分かるように to cc bcc を使って、送信先を複数(最大16件まで)指定することができます。

/*
   Email client sketch for Arduino
   Using SMTP2GO Server
*/

#include <SPI.h>
#include <Ethernet.h>
#include <Mail.h>         // https://github.com/nopnop2002/SMTPClient
#include <SMTPClient.h>   // https://github.com/nopnop2002/SMTPClient
 
// this must be unique
byte mac[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 }; 
 
char smtp_server[] = "mail.smtp2go.com";
int smtp_port = 2525;
char smtp_user64[] = "Email AddressをBase64に変換した文字列"; // Your Username of SMTP2GO
char smtp_pass64[] = "PasswordをBase64に変 換した文字列"; // Your Password of SMTP2GO
char mail_from[] = "Me<MailFrom@example.com>"; // Mail From
char mail_to[] = "You<MailTo@example.com>"; // Mail To
char mail_cc[] = "You<MailCc@example.com>"; // Mail Cc
char mail_bcc[] = "You<MailBcc@example.com>"; // Mail Bcc

EthernetClient ethClient;
SmtpClient smtpClient(&ethClient, smtp_server, smtp_port);
 
void setup()
{
  Serial.begin(9600);
  Serial.print("Ethernet.begin....");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    while(1) {}
  }
  Serial.println("ok....");
  Serial.print("localIP: ");
  Serial.println(Ethernet.localIP());
  Serial.print("subnetMask: ");
  Serial.println(Ethernet.subnetMask());
  Serial.print("gatewayIP: ");
  Serial.println(Ethernet.gatewayIP());
  Serial.print("dnsServerIP: ");
  Serial.println(Ethernet.dnsServerIP());
  Serial.println(F("Ready. Press 'e' to send."));
}
 
void loop()
{
  byte inChar;
  Mail mail;

  inChar = Serial.read();
  if(inChar == 'e') {
    mail.login(smtp_user64);
    mail.password(smtp_pass64);
    mail.from(mail_from);
    mail.to(mail_to);
    mail.cc(mail_cc);
    mail.bcc(mail_bcc);
    mail.subject("Arduino email test");
    mail.body("This is from my Arduino!\r\nUsing SMTPClient library");
    if (smtpClient.send(&mail)) {
      Serial.println(F("Email sent"));
      Serial.println(F("Ready. Press 'e' to send."));
    } else {
      Serial.println(F("Email failed"));
    }
  }
}

このスケッチを実行するとArduinoのシリアルモニターに以下が表示されます。



ここまで表示されたら「e」を送信します。



送信先に「Arduino email test」のメールが届いているはずです。
ライブラリ化した分、前回よりもすっきりしました。

続く
....