2017-08-02 67 views
0

我無法在Google或Mailgun支持上找到任何有關如何使用Powershell發送附件的答案。發送沒有附件的郵件適用於Mailgun和Powershell。這是我的代碼。使用Powershell發送帶有Mailgun的附件

 $apikey = "key-1342323f7d35352fa4dda3af3ca10e" 
     $idpass = "api:$($apikey)" 
     $basicauth = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($idpass)) 
     $headers = @{ 
      Authorization = "Basic $basicauth"; 
     } 
     $url = "https://api.mailgun.net/v3/sandboxac77741768d442323b96495501ac24b.mailgun.org/messages" 
     $mailbody = @{ 
      from = "Mailgun Sandbox <[email protected]>"; 
      to = "[email protected]"; 
      subject = "Testing mail"; 
      text = "Email body here"; 
      attachment = "D:\temp\logfile.txt"   
     } 
     Invoke-RestMethod -Uri $url -Method Post -Headers $headers -Body $mailbody -ContentType "multipart/form-data" 

這導致: 調用-RestMethod:遠程服務器返回錯誤:(400)錯誤的請求

+1

如果這是您的實際API密鑰,您可能想繼續並立即撤銷它:-) –

+0

這不是我的實際:) –

回答

0

特別感謝https://stackoverflow.com/users/213135/alex從誰偷走了我的代碼。

function ConvertTo-MimeMultiPartBody { 
    param([Parameter(Mandatory=$true)][string]$Boundary, [Parameter(Mandatory=$true)][hashtable]$Data) 

    $body = ""; 
    $Data.GetEnumerator() |% { 
     $name = $_.Key 
     $value = $_.Value 

     $body += "--$Boundary`r`n" 
     $body += "Content-Disposition: form-data; name=`"$name`"" 
     if ($value -is [byte[]]) { 
      $fileName = $Data['FileName'] 
      if(!$fileName) { $fileName = $name } 
      $body += "; filename=`"$fileName`"`r`n" 
      $body += 'Content-Type: application/octet-stream' 
      $value = [System.Text.Encoding]::GetEncoding("ISO-8859-1").GetString($value) 
     } 
     $body += "`r`n`r`n" + $value + "`r`n" 
    } 
    return $body + "--$boundary--" 
} 

$emaildomain = "example.com" 
$apikey = "key-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" 
$url = "https://api.mailgun.net/v2/$($emaildomain)/messages" 
$headers = @{ 
    Authorization = "Basic " + ([System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("api:$($apikey)"))) 
} 

$email_parms = @{ 
    from = "[email protected]"; 
    to = "[email protected]"; 
    subject = "My Test Email"; 
    text = 'Your email does not support HTML.'; 
    html = "Hello World!"; 
    filename = "example.pdf" 
    attachment = ([IO.File]::ReadAllBytes("c:\example.pdf")); 
} 
$boundary = [guid]::NewGuid().ToString() 
$body = ConvertTo-MimeMultiPartBody $boundary $email_parms 
Invoke-RestMethod -Uri $url -Method Post -Headers $headers -Body $body -ContentType "multipart/form-data; boundary=$boundary"