2017-08-02 39 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"