【PowerShell】SendGrid Web API でメール送信


ここではPowerShellを使用しているが、Javaなど他の言語ならライブラリが用意されているので、そちらを使う方が簡単だと思われる。

APIキーを取得する

SendGridのダッシュボードへログインし、左側のメニューで「API Keys」を選ぶ。

APIキー自体は、作成直後の画面からしか取得できないので注意。キーを無くしてしまった場合は、作り直さなくてはいけない。

APIキーにつける権限は、「Mail Send」のみあればOK。

Web API の仕様

SendGrid v3 API Documentation の Mail Send

PowerShell

Invoke-RestMethodを使う。

サンプル
function main() {

    # 添付ファイルを読込み、Base64でエンコードする
    $attach = "01.png"
    $attachContent = [System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes($attach))

    $url = "https://api.sendgrid.com/v3/mail/send"

    # ヘッダーの内容はAPIキーとcontent-typeでほぼ固定
    $headers = @{
        "authorization" = "Bearer [APIキー]"
        "content-type" = "application/json"
    }

    $body = @{
        "personalizations" = @(
            @{
                "to" = @(
                    @{"email" = "[email protected]" }
                )
            }
        )
        "subject" = "件名テスト"
        "content" = @(
            @{"type" = "text/plain"
              "value" = "本文テスト"}
        )
        "attachments" = @(
            @{
                "content" = $attachContent
                "filename" = "01.png"
            }
        )
        "from" = @{"email" = "[email protected]"}
    }

    # オブジェクトをJsonへ変換する。その際、Depthを指定して、深い階層も変換されるようにする。
    $bodyJson = $body | ConvertTo-Json -Depth 20

    # JsonをUTF-8へ変換する。変換せずにPOSTすると、日本語が文字化けする。
    $bodyBytes = [System.Text.Encoding]::UTF8.GetBytes($bodyJson)

    $res = Invoke-RestMethod -Uri $url -Method Post -Headers $headers -Body $bodyBytes
}

上記サンプルは決まり切ったメールを送る場合に使える。
関数化して、宛先、本文、添付ファイルを指定できるようにしたバージョンは、下記GitHubに作成しておいた。
https://github.com/vicugna-pacos/ps-mail-sendgrid

おまけ:Web API vs SMTP

Web API or SMTP Relay: How Should You Send Your Email? | SendGrid

Web APIの方をお勧めされている。