【PowerShell】SendGrid Web API でメール送信
8052 ワード
ここでは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の方をお勧めされている。
Author And Source
この問題について(【PowerShell】SendGrid Web API でメール送信), 我々は、より多くの情報をここで見つけました https://qiita.com/vicugna-pacos/items/3b19a9d32ea70c73c259著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .