Calling sendmail from PowerShell on Linux

Share on:

I haven't blogged about it a lot, but I am trying to learn what I can about PowerShell on Linux. I feel like more and more services are headed to the cloud, and (even in Azure) will be able to run on Linux devices. Being able to write portable scripts to move between what I manage today, and what I may be asked to manage in the future, can't be anything but beneficial.

I spent about an hour working on getting PoSH to successfully call sendmail in Linux, and then realized I was being an idiot. I didn't have any specific reason in mind, just a self-created task. This post is out there for everyone else who tries to do it the same way I did so that you can get to a better answer sooner than I did.

First what I did wrong. For those who haven't used it in a long time, or perhaps never used it, sendmail works by executing something like the following at a command line:

1sendmail -f
2From: Chris Kibble <>
3Subject: Hey man
4Hey, thanks for all your help recently!

That period at the end is needed and is your way of telling sendmail (or perhaps really the SMTP server?) that your message is over. Since PS on Linux has a Start-Process command just like Windows, or I guess more accurately I should say that PowerShell 6.x has Start-Process, I thought I could do something like this:

1$msgArguments = "-f"
2$msgArguments += "From: Chris Kibble <>"
3$msgArguments += "Subject: Hey man"
4$msgArguments += "Hey, thanks for all your help recently!"
5Start-Process sendmail -arguments $msgArguments

When that didn't work, I realized that I missed some line breaks, so I added first some carriage returns and line feeds after each line, but still no dice. I then tried with just a carriage return, and then with just a line feed, but still nothing. A message was going through, but it was coming from "root@" and had nothing in the subject or body.

After an hour, it hit me. The message itself isn't part of any argument, it's what you enter in your interactive session with the sendmail process! Armed with that eureka moment, I instead created a text file called test.txt (sorry, still using Windows extensions in a Linux world) with the following content:

1From: Chris Kibble <>
2Subject: Hey man
3Hey, thanks for all your help recently!  

And then called sendmail like so:

1Start-Process sendmail -arguments "-f" -RedirectStandardInput test.txt

Voila, message sent & received!

Have you come up with better ways to do this? Some other integration between PS and sendmail/postfix? Let me know in the comments.

No comments