Using Python and Powershell to email within Windows Environment

I was working on a project to perform some logic and then send an email (from a Windows environment) when certain conditions were met. Here are a couple things I ran into.

  1. I had a hard time finding useful information on sending email via Python and Exchange.
  2. I didn’t want to store my credentials anywhere.

I decided to use Powershell to send the email. The largest benefit was that I could send an email via Powershell on behalf of certain accounts without credentials. This comes in handy if you are using a noreply address to send out reports or notifications. Here’s what the Powershell script looked like to send the email.

$To = "First Last <>"
$From = "FromAddress <>"
$Cc = "First Last <>"
$Subject = "Outdated Reports on Server"
$body = @"
Detected outdated reports:
\\Server\Folder\ "outdated_reports.txt"

This script originates from \\Server\ScriptsFolder

Send-MailMessage -To $To  -From $From -Cc $Cc -Subject $Subject -body $body -SmtpServer ""

Link to Github

You can use Python to call cmd commands or even Powershell scripts. Here I use subprocess.Popen to perform this task.

p = subprocess.Popen(['powershell.exe', '-ExecutionPolicy', 'ByPass', r'C:\Scripts\SendEmail.ps1'])

Link to Github

Notice this… “-ExecutionPolicy Bypass” I ended up having to use this switch to launch the script from a server. The server had strict execution policies set. Ideally, you want to figure out how to sign your scripts and configure your server to execute signed scripts. However, it’s kind of a pain and I was in a hurry.

(This seems like a huge security flaw. “Ummmmm yeahhhhh… I’m gonna need you to bypass the security policies… and let me execute some code that would be great… M’kay?”)

Checkout the docs to learn more about the subprocess module and Popen.communicate.

This particular program had to be run daily so I just used Task Scheduler to run it every morning. If this was helpful to you, send me a tweet on twitter or send me an email.