As of version 2.0, PowerShell comes with a cmdlet that allows you to send emails. It is relatively simple to pass the elements of a message as parameters and to authenticate interactively at an SMTP server. Things get a bit tricky if you want to send emails from a script without the intervention of a user.

Since the introduction of the Send-MailMessage cmdlet, PowerShell offers an integrated feature for sending emails without the need to use .NET classes, as was required in PowerShell 1.0. The old command interpreter, cmd.exe, doesn’t offer any features for this purpose, so you have to use external programs such as blat.exe.

Parameters for all elements of a message ^

Send-MailMessage supports all the parameters you need to use the cmdlet as an email client.

Send-MailMessage [-To] <string[]> [-Subject] <string> -From <string> [[-Body] <string>] [[-SmtpServer] <string>] [-Attachments <string[]>] [-Bcc <string[]>] [-BodyAsHtml] [-Cc <string[]>] [-Credential <PSCredential>] [-DeliveryNotificationOption {None | OnSuccess | OnFailure | Delay | Never}] [-Encoding <Encoding>] [-Priority {Normal | Low | High}] [-UseSsl] <CommonParameters>]

In most cases, not all the parameters are required, and sometimes you don’t want to use parameters to pass relevant information to Send-MailMessage. Depending on the particular case, the content of the email can come from a log file that you want to analyze with other PowerShell cmdlets, or perhaps you want to load the attachments from the contents of a folder.

Minimum requirements of Send-MailMessage ^

A simple call that contains all required parameters might look like this:

Send-MailMessage -to "recipient@contoso.com" -from "PowerShell <sender@contoso.com>" -Subject "Test" -body "Test for Send-MailMessage"

This command will only be successful if you stored the SMTP server address in the variable $PSEmailServer, as in the example below:

$PSEmailServer = "smtp-server.com"

Another option would be to pass the information with the parameter -SmtpServer. If you send emails frequently with this method, it might make sense to store the default SMTP server address in your PowerShell profile.

Interactive authentication on the SMTP server ^

In the above example, the cmdlet would try to authenticate on the SMTP server with the credentials of the logged-in user. If this isn’t possible, you have to pass the PSCredential object to authenticate at the server (only if the server requires authentication).

The easiest way is to pass the username with the parameter -Credential. PowerShell will then open a dialog window where you can enter your credentials.

Send-MailMessage -to "recipient@contoso.com" -from "PowerShell <sender@contoso.com >" -Subject "Test" -body "Test for Send-MailMessage" -Credential "MailUser"

Interactive authentication at the SMTP server

Interactive authentication at the SMTP server

After a successful authentication, the message will be sent.

SMTP authentication without user intervention ^

Interactive authentication is suboptimal if a script is supposed to send emails without user interaction. In this case, you have to find a way to automate the authentication process.

The popular method of other scripting languages to pass passwords in clear text is not permitted in PowerShell. It is also not possible to store the PSCredential objects in a file. To create the PSCredential object, you have to pass a username and read the password from an encrypted file. To store the password in an encrypted file, you can use the Get-Credential cmdlet:

(Get-Credential).password | ConvertFrom-SecureString > MailPW.txt

The Get-Credential cmdlet asks the user to enter username and password. Then, it creates a PSCredential object from which the password is extracted and stored in the encrypted file MailPW.txt.

Create PSCredential object before sending the email ^

Before you call Send-MailMessage, you have to create the PSCredential object by reading the password from the file and converting it back to a secure string:

$pw = Get-Content .\MailPW.txt | ConvertTo-SecureString
$cred = New-Object System.Management.Automation.PSCredential "MailUser", $pw

To authenticate the user, you can then pass the variable $cred to Send-MailMessage with the parameter -Credential.

Send-MailMessage -Credential $cred -to "recipient@contoso.com" -from "PowerShell <sender@contoso.com>" -Subject "Test" -body "Test for Send-MailMessage"

You could also store the commands for creating the PSCredential object in your PowerShell profile to have it always available when PowerShell starts.

Special characters ^

A third obstacle is special characters. If you omit the parameter -Encoding, the default encoding configuration is ASCII. If the subject contains language-specific special characters, they will be garbled. To be on the safe side, you can add the parameter -Encoding to use UTF8 instead of ASCII.

-encoding ([System.Text.Encoding]::UTF8)

Attach files with a pipe ^

If you don’t want to type a list of files to attach them to your email with the -Attachments parameter, you can import them from a folder and then pass them through a pipe to Send-MailMessage.

Get-ChildItem f*.jpg | Send-MailMessage -Credential $cred -to "recipient@contoso.com" -from "PowerShell <sender@contoso.com>" -Subject "Test" -body "Test for Send-MailMessage" -encoding ([System.Text.Encoding]::UTF8)

Send-MailMessage offers various additional options; however, the discussed examples should cover the majority of cases. Also noteworthy are -BodyAsHtml and -UseSSL, which allow you to send HTML emails and establish an SSL connection with the SMTP server.

10 Comments
  1. dastagiri 7 years ago

    mailuser name is email address or window user ?

  2. It is the user account that you use to authenticate at the mail server.

  3. david dc 7 years ago

    How do I put variables into subject or body of the email? I want amount of files in subject and in body of the email. Thanks!

    $Files = @(Get-ChildItem $root -Filter *.pdf -recurse )
    if ($Files.length -eq 0) {
    write-host " no files to delete."
    } else {
    Write-Host Found $Files.Count PDF files
    # send alert emails
    Send-MailMessage -From "Xtender@colo.edu" -To "chang@colo.edu" -Subject "$Files.Count PDF files found not processed" -Body "$Files.Count PDF files found not being processed in Xtender server." -SmtpServer mail.colo.edu
    }

  4. David, if you want to access a property of a variable in a double quoted string, you have to enclose it like this $().

    This is how your subject should look like: “$($Files.Count) PDF files found not processed”

  5. Eydie 6 years ago

    I have a few scripts to manage AD accounts. I'd like to add a wait command to send the email notification after 15 minutes giving time for the Mailbox to sync with AD. I'm probably using older PS Commands but they work. I tried the DeferredDeliveryTime but it's not recognized.
    This is part of what I use to send the email: Suggestions?
    $smtpServer = "ourmailhost.ours.yes"
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)
    $msg = new-object Net.Mail.MailMessage
    $msg.From = ("newaccount@ppsk12.net")
    $msg.BCC.Add("newaccount@ppsk12.net")
    $msg.subject = $subject
    $msg.IsBodyHTML = $true
    $msg.body = $body
    $smtp.Send($msg)

  6. william 3 years ago

    I am still getting the error "the SMTP server requires a secure connection or the client was not authenticated." I have verified that I typed in the user/pass correctly and I am also using the -UseSsl.

    • It could be that your mail server uses an uncommon port for SSL/TLS. Check the documentation and then add the port with the -Port parameter.

  7. William, is your mail server one of the ones that does a POP/IMAP check before allowing you to send?

    David F.

  8. Sathiya 3 years ago

    Hi,

    Please advise how to stop repeated email for an already trigger email alert for 1 hour, am using log file string match to trigger mail alert using powershell

    Thanks,

    Sathiya.

    • @Sathiya

      Your problem does not seem to be related to the topic of this article, but rather to an application which is sending mails.

      Please open a new topic in the IT Administration forum.

Leave a reply

Please enclose code in pre tags

Your email address will not be published. Required fields are marked *

*

© 4sysops 2006 - 2021

CONTACT US

Please ask IT administration questions in the forums. Any other messages are welcome.

Sending

Log in with your credentials

or    

Forgot your details?

Create Account