「東雲 忠太郎」の平凡な日常のできごと

2024/02/26(月)03:56

OutLookGraphAPIでメールを送信するコード

Graph API(619)

# アクセストークン取得のための認証情報 $client_id = "YOUR_CLIENT_ID" $client_secret = "YOUR_CLIENT_SECRET" $tenant_id = "YOUR_TENANT_ID" $redirect_uri = "http://localhost" # アクセストークンを取得するためのパラメータを設定 $authParams = @{     client_id     = $client_id     scope         = "https://graph.microsoft.com/.default"     response_type = "code"     redirect_uri  = $redirect_uri } # ユーザーにログインしてアクセストークンを取得 $authUrl = "https://login.microsoftonline.com/$tenant_id/oauth2/v2.0/authorize?" + ($authParams | foreach { "$($_.Name)=$($_.Value)" }) Start-Process -FilePath $authUrl # ユーザーによる認証と承認が完了し、リダイレクトされたら、リダイレクトURIからコードを取得します。 # コードを入力 $code = Read-Host -Prompt "Enter the authorization code" # アクセストークンを取得 $tokenParams = @{     client_id     = $client_id     scope         = "https://graph.microsoft.com/.default"     code          = $code     redirect_uri  = $redirect_uri     grant_type    = "authorization_code"     client_secret = $client_secret } $tokenResponse = Invoke-RestMethod -Method Post -Uri "https://login.microsoftonline.com/$tenant_id/oauth2/v2.0/token" -Body $tokenParams # アクセストークンを取得 $accessToken = $tokenResponse.access_token if (-not [string]::IsNullOrEmpty($accessToken)) {     Write-Host "Access Token: $accessToken"     # メールの情報     $emailSubject = "Test Email"     $emailBody = "This is a test email sent via PowerShell."     $recipientEmailAddress = "recipient@example.com"     $emailJson = @{         message = @{             subject = $emailSubject             body = @{                 contentType = "Text"                 content = $emailBody             }             toRecipients = @(                 @{                     emailAddress = @{                         address = $recipientEmailAddress                     }                 }             )         }         saveToSentItems = "true"     } | ConvertTo-Json     $sendEmailUrl = "https://graph.microsoft.com/v1.0/me/sendMail"     $sendEmailResponse = Invoke-RestMethod -Uri $sendEmailUrl -Method Post -Headers @{         Authorization = "Bearer $accessToken"         'Content-Type' = 'application/json'     } -Body $emailJson     if ($sendEmailResponse) {         Write-Host "Email sent successfully."     } else {         Write-Host "Failed to send email."     } } else {     Write-Host "Failed to retrieve access token." }

続きを読む

このブログでよく読まれている記事

もっと見る

総合記事ランキング

もっと見る