Codeworks Notes

 2019-07-08

 2020-04-25

Linux
Raspberry Pi

SSMTPを使ったメール送信

概要

Raspberry Pi にメール送信をさせる方法のひとつです。
postfix + mail コマンドを使ったメール送受信もありますが、既存メールアドレスを使ってメールソフトを使うように送信できるようにし、通知などを送ったりする限定的な用途では ssmtp を使うとよいでしょう。

1. メールアドレスの準備

ここでは XSERVER のメールアドレスを取得しました。

2. ssmtpのインストール

コケる場合があるのでパッケージを最新のものにしましょう。

apt-get update
apt-get upgrade

終わったらssmtpをインストールします。

apt-get install -y ssmtp

3. ssmtp.confの設定

設定ファイルをテキストエディタで開き、メール送信情報を補完します。

#
# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
root=noreply@hogehoge.com // 自分のメールアドレス 
 
# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named mail.domain.com
mailhub=sv****.xserver.jp:587 // sv****は自分のサーバ番号にする。
# ポートはIMAPの場合465、SMTPは587
 
# Where will the mail seem to come from?
#rewriteDomain=
 
# The full hostname
hostname=hogehoge.com // メールアドレスの@以降として扱われる
 
# Are users allowed to set their own From: address?
# YES - Allow the user to specify their own From: address
# NO - Use the system generated From: address
#FromLineOverride=YES
 
AuthUser=noreply@hogehoge.com // 自分のメールアドレス
Authpass=password // 自分のメールパスワード
UseSTARTTLS=YES

メールアドレスの「@」より左側は実行ユーザー名になります。
root が実行すれば root が挿入されるので、必要に応じて useradd を行ってください。

4. メールの送信

/etc/ssmtp/testmail.txt を用意してテストしてみましょう。

From:noreply@hogehoge.com // 自分のメールアドレス
to:hoge@hogefuga.com // 送信先のメールアドレス
Subject:test // 件名

これはテストメールです。 // 本文です。改行も使えます。
sendmail -t < /etc/ssmtp/testmail.txt

上記コマンドで送信します。
正しく受信できるか確認しましょう。

5. シェルスクリプトの書き方

cron で自動実行させたい場合もあると思いますので、シェルスクリプトの記述例を。
送信プロセスを関数化しています。

#!/bin/bash

export PATH=$PATH:/usr/sbin

mail_to="hoge@gmail.com"
mail_from="noreply@hogehoge.com"
subject="メール件名"

mail_send () {

cat << EOD | sendmail -t
From: ${mail_from}
To: ${mail_to}
Subject: ${subject}

これはテストメールです。
変数とかもバリバリ入ります。

EOD
}

mail_send

exit 0