In this tip, you will find a convenient and simple solution for preparing (without sending) emails from Windows in Outlook.
Introduction
I was struggling for a while now to find a perfect solution for preparing emails from Windows using Windows batch. I was mostly using mailto
command, but it has many limitations, the most annoying of which was always that it was clipping my messages (seems to withstand only a limited number of characters) + it does not support HTML.
Recently, I stumbled upon a simple solution in PowerShell that uses Outlook instance, I adjusted the solution a bit and created a CMD wrapper that can be called as a program from any Windows batch.
Using the Code
The solution contains two files, one is Powershell script (.ps1), and the other is the .cmd wrapper.
The message opens as new mail in Outlook, but does not get sent automatically (user gets to check how it looks before sending).
Windows Batch
A Windows batch wrapper that takes in the arguments and passes them to the Powershell call (script).
:: Args:
:: %1 = To
:: %2 = Cc
:: %3 = Subject
:: %4 = Body
:: %5 = HTML (True / False)
@echo off
pushd "%~dp0"
set "to=%~1"
if "%to%"=="" ( set /p "to=To: " )
set "cc=%~2"
if "%cc%"=="" ( set /p "cc=Cc: " )
set "subject=%~3"
if "%subject%"=="" ( set /p "subject=Subject: " )
set "body=%~4"
if "%body%"=="" ( set /p "body=Body: " )
set "html=%~5"
if "%html%"=="" ( set /p "html=HTML (y/n)? " )
if /i "%html%"=="y" ( set html=true )
if /i not "%html%"=="y" ( set html=false )
if not "to"=="" ( set "to=-to "%to%"" )
if not "cc"=="" ( set "cc=-cc "%cc%"" )
if not "subject"=="" ( set "subject=-subject "%subject%"" )
if not "body"=="" ( set "body=-body "%body%"" )
if not "html"=="" ( set "html=-html %html%" )
Powershell.exe -executionpolicy remotesigned -File preparemail.ps1 %to% %cc% %subject% %body% %html%
Powershell Script
A Powershell script which takes the needed parameters (uses hardcoded defaults if they are empty), creates a new Outlook object, and then creates a new email message. It supports both plain text and HTML body.
param (
[string]$to = "default@default.com",
[string]$cc = "default@default.com",
[string]$subject = "default subject",
[string]$body = "default body",
[switch]$html = $false
)
$ol = New-Object -comObject Outlook.Application
$mail = $ol.CreateItem(0)
$mail.To = $to
$mail.Cc = $cc
$mail.Subject = $subject
if($html) {
$mail.HTMLBody = $body
} else {
$mail.Body = $body
}
$inspector = $mail.GetInspector
$inspector.Display()
Note: If you are using HTML body, then you need to pass the body
argument as HTML code.