Last active
December 24, 2015 15:28
-
-
Save kazuhito-m/6819992 to your computer and use it in GitHub Desktop.
サーバに入った際「コマンドを自由にビルド・パッケージインストール出来ない場合」に補うための"超原始的"スクリプト群(bash)。 メール送信。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# メール送信関数 | |
# | |
# smtpサーバ未設定のmailコマンドや、sendmailコマンドが無いサーバでも実行できるように、 | |
# bash & 少しのコマンドで送れる、原始的なものです。 | |
# | |
# 前提/制約 | |
# | |
# * 右記のコマンドが実行できること expect telnet cat echo whoami hostname base64 | |
# * 件名(Subject)には、英数字記号しか指定できない。日本語は文字化ける。 | |
# * 一度に複数件の宛先んには送れない。(同一コマンドを連打するしかない) | |
# * 本文はかならずテキストファイルを用意しなくてはならない。 | |
# * sasl_authなどユーザ認証に対応しない。ポート指定で即送れるsmtpサーバのみOK。 | |
# * 本文にダブルクオートが含まれていると送信できない。 | |
# | |
# 使い方 | |
# send_mail smtpサーバ port番号 送信先メールアドレス 件名(Subjct) 本文の記述が入ったテキストファイル名 | |
# | |
function send_mail() { | |
# この関数内で使用する関数チェック | |
for cmd in expect telnet cat ; do | |
which $cmd > /dev/null | |
if [ "$?" -ne 0 ] ; then | |
echo "内部で必要なコマンド $cmd が無いため、メール送信を実行できません。" | |
exit 1 | |
fi | |
done | |
# 引数を意味ベースで収容 | |
smtp_server=$1 | |
smtp_port=$2 | |
from_addr=`whoami`'@'`hostname` | |
to_addr=$3 | |
subject=$4 | |
echo $subject | |
mail_content='' | |
# 引数のファイルをチェック | |
content_file=$5 | |
if [ -e $content_file ]; then | |
mail_content=`base64 $content_file` | |
else | |
# 存在しない場合 | |
echo "メール本文ファイル $content_file は存在しません。" | |
exit 2 | |
fi | |
# 実送信処理。 | |
expect -c " | |
set timeout 10 | |
spawn telnet $smtp_server $smtp_port | |
expect -re \"220.*\n\" | |
send \"HELO exsample.com\r\" | |
expect -re \"250.*\n\" | |
send \"MAIL FROM:$from_addr\r\" | |
expect -re \"250.*\n\" | |
send \"RCPT TO:$to_addr\r\" | |
send \"DATA\r\" | |
expect -re \"354.*\n\" | |
send \"From:$from_addr\r\" | |
send \"To:$to_addr\r\" | |
send \"Subject:$subject\r\" | |
send \"Content-Type: text/plain; charset=utf-8\r\" | |
send \"Content-Transfer-Encoding: base64\r\" | |
send \"\r\" | |
send \"$mail_content \" | |
send \"\r\" | |
send \".\r\" | |
expect -re \"250.*\n\" | |
send \"QUIT\r\" | |
expect -re \"221.*\n\" | |
" | |
exit 0 | |
} | |
#引数があったら、このシェルスクリプト自体が実行モードで動く。 | |
if [ "$#" -ne 0 ] ; then | |
send_mail "$1" "$2" "$3" "$4" "$5" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@iso2022jp さんのアイディアを元にテキストファイルの内容を”base64”コマンドでエンコード、SMPTヘッダ側にbase64のエンコーディング指定。(出来る限りの環境非依存の文字化け対策)