LoginSignup
1
1

Powershellを使って定型メールに必要な情報を入力した上でメールで通知する処理を効率化する

Last updated at Posted at 2023-10-23

背景

入社処理とかで、システムのアカウント情報を複数人宛にメールで通知する際、一人一人に対してメール本文を作成して送るのが面倒だったので作成。

仕組み

Powershellで標準入力待ちの状態でプログラムを起動させ、メールに必要な情報を入力して定例のメール文を作成して送信する。

コード

# スクリプトの実行ログを生成、取得開始
$filename = Get-Date -Format "yyyy-MMdd-HHmmss"
Start-Transcript -Path $filename -Append

[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

    # 標準入力で必要な情報を入力する
    do {
        $name = Read-Host "`r`n名前を入力してください"
        $ma = Read-Host "`r`nメールアドレスを入力してください"
        $pass = Read-Host "`r`nパスワードを入力してください"
        $text = "${name} さん
    
        ■メールアドレス:${ma}
        ■パスワード:${pass}"
    
        # 送信するメール本文を表示
        Write-Output "

        送信するメール文はこんなかんじ!
        
        ↓ ↓ ↓
        
        ----
        
        $text
        
        ----"
    
        $to = $ma
        $to1 = ""  # ここに宛先アドレスを入力してください
        $from = ""  # ここに送信元メールアドレスを入力してください
        $smtp = ""  # ここにSMTPサーバーを入力してください
        $subject = "XXX"
        [string]$body = $text
    
        $input = Read-Host "`r`nメールを送信しますか(yes or no)?"
    
        # yesだったらメールを飛ばす
        If ($input -eq "yes") {
            Send-MailMessage -To $to -From $from -SmtpServer $smtp -Subject $subject -Body $body -Encoding UTF8
            Send-MailMessage -To $to1 -From $from -SmtpServer $smtp -Subject $subject -Body $body -Encoding UTF8
            Write-Output "`r`nメールの送信が完了しました!`r`n"
    
        # noたったらメールの送信を中止する
        } ElseIf ($input -eq "no") {
            Write-Output "`r`nメールの送信を中止しました!`r`n"
        }
    
        # 処理を継続する場合はyesを入力する。yesの場合最初の標準入力待ちの状態に戻る。
        $restart = Read-Host "`r`n処理を継続しますか(yes or no)?"
    } while ($restart -eq "yes")

# スクリプトの実行ログの取得終了
Stop-Transcript

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1