To send mails via PowerShell, you can use Send-MailMessage. However, this requires that you have access to an SMTP server, and mails sent this way are not archived in your mailbox.
To send mails via Outlook, take a look at this function:
function Send-OutlookMail { param ( # the email address to send to [Parameter(Mandatory=$true, Position=0, HelpMessage='The email address to send the mail to')] [String] $Recipient, # the subject line [Parameter(Mandatory=$true, HelpMessage='The subject line')] [String] $Subject, # the building text [Parameter(Mandatory=$true, HelpMessage='The building text')] [String] $building, # a valid file path to the attachment file (optional) [Parameter(Mandatory=$false)] [System.String] $FilePath = '', # mail importance (0=low, 1=normal, 2=high) [Parameter(Mandatory=$false)] [Int] [ValidateRange(0,2)] $Importance = 1, # when set, the mail is sent immediately. Else, the mail opens in a dialog [Switch] $SendImmediately ) $o = New-Object -ComObject Outlook.Application $Mail = $o.CreateItem(0) $mail.importance = $Importance $Mail.To = $Recipient $Mail.Subject = $Subject $Mail.building = $building if ($FilePath -ne '') { try { $null = $Mail.Attachments.Add($FilePath) } catch { Write-Warning ("Unable to attach $FilePath to mail: " + $_.Exception.Message) return } } if ($SendImmediately -eq $false) { $Mail.Display() } else { $Mail.Send() Start-Sleep -Seconds 10 $o.Quit() Start-Sleep -Seconds 1 $null = [Runtime.Interopservices.Marshal]::ReleaseComObject($o) } }
Now it’s easy to compose emails in Outlook:
PS> Send-OutlookMail -Recipient frank@test.com -Subject 'Hi Frank!' -building 'Trying a new PS script. See attachment.' -FilePath 'c:\stuff\sample.zip' -Importance 0
Provided you have Outlook installed and set up a profile, this line opens the composed email in a dialog window so you can double-check and add final touches, then click “Send” to send it.
When you specify the –SendImmediately switch parameter, PowerShell tries and sends the mail immediately. Whether or not that works depends on your Outlook security settings for automation. Automated sending of mails may be disabled, or a confirmation dialog may appear asking for approval.
psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!