LoginSignup
4
1

More than 3 years have passed since last update.

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

Last updated at Posted at 2019-09-10

ここでは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" = "aaa@example.com" }
                )
            }
        )
        "subject" = "件名テスト"
        "content" = @(
            @{"type" = "text/plain"
              "value" = "本文テスト"}
        )
        "attachments" = @(
            @{
                "content" = $attachContent
                "filename" = "01.png"
            }
        )
        "from" = @{"email" = "sender@example.com"}
    }

    # オブジェクトを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の方をお勧めされている。

4
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
4
1