長時間計算の終了をGmailで通知する

Ubuntu上で長時間計算を実行し、終了時にGmailへ通知する方法。

1. msmtp のインストール

$ sudo apt update

$ sudo apt install msmtp ca-certificates

インストール時の

Enable AppArmor support?

には Yes でよい。


2. Gmail用 msmtp の設定

Googleアカウントで2段階認証を有効にし、アプリパスワードを作成する。

~/.msmtprc を作成:

defaults

auth           on

tls            on

tls_starttls   on

tls_trust_file /etc/ssl/certs/ca-certificates.crt


account gmail

host smtp.gmail.com

port 587

from YOUR_ADDRESS@gmail.com

user YOUR_ADDRESS@gmail.com

password YOUR_APP_PASSWORD


account default : gmail

自分の環境に合わせて変更する箇所

以下の2つは必ず自分のものに置き換える。

権限を制限する。

$ chmod 600 ~/.msmtprc

送信テスト:

$ printf 'From: YOUR_ADDRESS@gmail.com\nTo: YOUR_ADDRESS@gmail.com\nSubject: msmtp test\n\nHello from Ubuntu.\n' \

    | msmtp YOUR_ADDRESS@gmail.com


3. 汎用終了通知コマンド notifyrun

~/local/bin/notifyrun を作成:

#!/usr/bin/env bash


MAIL_TO="YOUR_ADDRESS@gmail.com"

MAIL_FROM="YOUR_ADDRESS@gmail.com"


if [ "$#" -eq 0 ]; then

    echo "Usage: notifyrun command [args ...]" >&2

    exit 2

fi


start_epoch=$(date +%s)

start_time=$(date '+%Y-%m-%d %H:%M:%S %Z')

workdir=$(pwd)

host=$(hostname)


printf -v command_str '%q ' "$@"

command_str=${command_str% }


"$@"

status=$?


end_epoch=$(date +%s)

end_time=$(date '+%Y-%m-%d %H:%M:%S %Z')


elapsed=$((end_epoch - start_epoch))

hours=$((elapsed / 3600))

minutes=$(((elapsed % 3600) / 60))

seconds=$((elapsed % 60))

elapsed_str=$(printf '%02d:%02d:%02d' "$hours" "$minutes" "$seconds")


if [ "$status" -eq 0 ]; then

    result="SUCCESS"

else

    result="FAILED"

fi


subject="[$result] $(basename "${1}") on ${host}"


{

    printf 'From: %s\n' "$MAIL_FROM"

    printf 'To: %s\n' "$MAIL_TO"

    printf 'Subject: %s\n' "$subject"

    printf '\n'

    printf 'Command finished.\n\n'

    printf 'Result      : %s\n' "$result"

    printf 'Exit status : %d\n' "$status"

    printf 'Command     : %s\n' "$command_str"

    printf 'Directory   : %s\n' "$workdir"

    printf 'Host        : %s\n' "$host"

    printf 'Start       : %s\n' "$start_time"

    printf 'End         : %s\n' "$end_time"

    printf 'Elapsed     : %s\n' "$elapsed_str"

} | msmtp "$MAIL_TO"


exit "$status"

ここでも、YOUR_ADDRESS@gmail.com を自分のGmailアドレスに変更する。

実行権限を付与:

$ chmod +x ~/local/bin/notifyrun

~/local/bin が PATH に入っていない場合は ~/.bashrc に追加:

$ export PATH="$HOME/local/bin:$PATH"

反映:

$ source ~/.bashrc


4. 使用例

FPLO:

$ notifyrun fplo > fplo.scf.out 2>&1 &

RPA:

$ notifyrun rpa > rpa.out 2>&1 &

MPI計算:

$ notifyrun mpirun -np 32 ./rpa rpa.ini > rpa.out 2>&1 &

端末やSSH接続を閉じる可能性がある場合:

$ nohup notifyrun fplo > fplo.scf.out 2>&1 &


5. 通知内容

終了時に以下の情報がGmailへ送られる。

Result      : SUCCESS

Exit status : 0

Command     : fplo

Directory   : /path/to/calculation

Host        : hostname

Start       : 2026-10-05 20:15:03 JST

End         : 2026-10-06 06:27:41 JST

Elapsed     : 10:12:38

これにより、任意の長時間計算を共通の方法で監視できる。