Skip to content

Instantly share code, notes, and snippets.

@ctigeek
Last active January 2, 2023 17:36
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ctigeek/d79484ccbaec7e71a837 to your computer and use it in GitHub Desktop.
Save ctigeek/d79484ccbaec7e71a837 to your computer and use it in GitHub Desktop.
Send an email using Mailgun in Powershell.
function Send-MailgunEmail($from, $to, $subject, $body, $emaildomain, $apikey) {
$idpass = "api:$($apikey)"
$basicauth = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($idpass))
$headers = @{
Authorization = "Basic $basicauth"
}
$url = "https://api.mailgun.net/v2/$($emaildomain)/messages"
$body = @{
from = $from;
to = $to;
subject = $subject;
text = $body
}
Invoke-RestMethod -Uri $url -Method Post -Headers $headers -Body $body
}
@yingdongzhang
Copy link

Is there a way to add attachments?

I've tried adding the header "Content-type" = "multipart/form-data"; and a attachment field to the $body, but Mailgun returns 400 bad request.

@jwalker55
Copy link

Is it possible to pass multiple tags (o:tag) using this method?

@ctigeek
Copy link
Author

ctigeek commented Jun 12, 2019

@jwalker55
In order to add multiple tags, you will need to build your own body string since the powershell hash created can't have multiple entries with the same name.

@jwalker55
Copy link

Any way you can point me in the right direction to start building a body string? Not sure where to start

@ctigeek
Copy link
Author

ctigeek commented Jun 12, 2019

@jwalker55
So it would be something like:
$body = "from=" + [uri]::EscapeDataString($from) + "&to="+[uri]::EscapeDataString($to) + "&subject=" + [uri]::EscapeDataString($subject) + "&text=" + [uri]::EscapeDataString($body)

Just follow the same pattern to add as many o:tag entries as you like.

When manually creating the body, you probably also need to add the content-type to $headers:
"Content-Type"="application/x-www-form-urlencoded".

@jwalker55
Copy link

Ahhh ok. Tremendous help. Thank you!

@s890542
Copy link

s890542 commented Jan 2, 2023

anyways to add attachment to email using mailgun ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment