LoginSignup
3
0

PowerShellで送信メールを作成する

Posted at

きっかけ

毎日メールで日報を送信するのですが、テキストファイルに入力した
本文、件名、宛先を1つずつペタペタ張り付けて作るのが面倒になり、
少しでも自動化しようと考えました。

エクセルのマクロを使えれば、日付や記載内容等をもっと自動化したり、
他の管理につかえたり出来るのですが、環境的にマクロを使えない為、
PowerShellを使う事にしました。

やりたかった事

  • 実行するとOutlookのメールを作成してくれる
  • テキストファイルに記載したものをメール本文に転記
  • 件名には送信する日付を埋め込む(フォーマット指定あり)
  • 宛先は固定
  • メールは作成してポップアップまで (自動送信はしない) ←ここ大事

スクリプトとテキストファイルの配置構成

スクリプトとテキストファイルの配置構成.jpg

MakeMail.ps1
# スクリプトを実行した年月日を取得
$currentDate = Get-Date
$year = $currentDate.Year
$month = $currentDate.Month
$day = $currentDate.Day

# フォルダとファイルのパスを構築
$folderPath = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath $year) -ChildPath $month"月"
$filePath = Join-Path -Path $folderPath -ChildPath "日報_$($currentDate.ToString('yyyyMMdd')).txt"

# フォルダが存在しない場合は作成
if (-not (Test-Path -Path $folderPath)) {
    New-Item -Path $folderPath -ItemType Directory
}

# テキストファイルを読み込む
if (Test-Path -Path $filePath) {
    $mailContent = Get-Content -Path $filePath -Raw
} else {
    Write-Host "Error: テキストファイルが見つかりません。"
    exit 1
}

# メールの件名を作成
$mailSubject = "業務報告 $($currentDate.ToString('yyyy.MM.dd')) 〇〇〇〇"

# メールの宛先を指定
$mailTo = "test@example.com"

# メール本文にテキストファイルの内容を張り付ける
$mailBody = $mailContent

# Outlookでメールを新規作成
$outlook = New-Object -ComObject Outlook.Application
$mail = $outlook.CreateItem(0)
$mail.Subject = $mailSubject
$mail.To = $mailTo
$mail.Body = $mailBody

# メールを送信せずに終了
$mail.Display() | Out-Null
3
0
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
3
0