Windows OS Hub
  • Windows
    • Windows 11
    • Windows Server 2022
    • Windows 10
    • Windows Server 2019
    • Windows Server 2016
  • Microsoft
    • Active Directory (AD DS)
    • Group Policies (GPOs)
    • Exchange Server
    • Azure and Microsoft 365
    • Microsoft Office
  • Virtualization
    • VMware
    • Hyper-V
  • PowerShell
  • Linux
  • Home
  • About

Windows OS Hub

  • Windows
    • Windows 11
    • Windows Server 2022
    • Windows 10
    • Windows Server 2019
    • Windows Server 2016
  • Microsoft
    • Active Directory (AD DS)
    • Group Policies (GPOs)
    • Exchange Server
    • Azure and Microsoft 365
    • Microsoft Office
  • Virtualization
    • VMware
    • Hyper-V
  • PowerShell
  • Linux

 Windows OS Hub / PowerShell / Send-MailMessage: Sending E-mails with PowerShell

March 17, 2024 PowerShellWindows 10Windows 11Windows Server 2019

Send-MailMessage: Sending E-mails with PowerShell

You can use the built-in Send-MailMessage cmdlet to send SMTP e-mails from PowerShell (previously you can use the .Net System.Net.Mail class to send e-mail messages). Send-MailMessage allows you to send messages with attachments, use HTML format for the body of the message, enable delivery notification, send a message to multiple recipients at once, etc. In this article, we’ll see how to use the Send-MailMessage cmdlet to send e-mail messages from within your PowerShell scripts.

Contents:
  • PowerShell Send-MailMessage Cmdlet: Parameters and Examples
  • Using Send-MailMessage with SMTP Auth and TLS/SSL
  • How to Send an Email via the Gmail SMTP with PowerShell?

PowerShell Send-MailMessage Cmdlet: Parameters and Examples

To get the syntax of the cmdlet, run this command:

get-help Send-MailMessage

Send-MailMessage [-To] <String[]> [-Subject] <String> [[-Body] <String>] [[-SmtpServer] <String>] [-Attachments <String[]>] [-Bcc <String[]>] [-BodyAsHtml] [-Cc <String[]>] [-Credential <PSCredential>] [-DeliveryNotificationOption {None | OnSuccess | OnFailure | Delay | Never}] [-Encoding <Encoding>] -From <String> [-Port <Int32>] [-Priority {Normal | Low | High}] [-UseSsl] [<CommonParameters>]
The Send-MailMessage cmdlet sends an email message from within Windows PowerShell.

Using the PowerShell Send-MailMessage cmdlet

Here are the main options:

  • From – is a sender address. You can send an email message on behalf of any email address if the SMTP server does not check the sender address (anonymous relay);
  • To – the recipient’s email address;
  • SMTPServer –the address of the SMTP server through which you want to send the e-mail.

The SMTP server address is not required if you set the mail server address in the $PSEmailServer environment variable:

$PSEmailServer = "smtp.woshub.com"

The following PowerShell command will send an e-mail with the specified subject and body to multiple recipients.

Send-MailMessage -From '[email protected]' -To '[email protected]','[email protected]' -Subject "Test Email Alert" -Body "This is email body text" –SmtpServer 'smtp.woshub.com'

You can send an email to one or more recipient mailboxes, to a Teams channel, or an address in an Exchange distribution group.

To make it easier to edit the attributes of a cmdlet, the Send-MailMessage command can be represented as follows:

Send-MailMessage `
-SmtpServer smtp.woshub.com `
-To '[email protected]','[email protected]' `
-From '[email protected]' `
-Subject "Test" `
-Body "Sending email using PowerShell" `
-Encoding 'UTF8'

Note that in the last command, we additionally set the UTF8 encoding for the email. Otherwise, if the email subject or body contains non-ANSI characters, they will be displayed incorrectly.

Windows PowerShell uses ANSI and ASCII encoding by default. If you’ve updated your PS version to PowerShell Core, keep in mind that this version already uses UTF-8 encoding by default.

You can specify multiple recipients by using the parameters:

  • To – the regular recipient’s email addresses;
  • Cc –  the email addresses to send a carbon copy (CC) of the email message;
  • Bcc – the e-mail addresses that will receive a copy of the e-mail but will not be listed as a recipient of the message.

You can enable a delivery notification for an email using -DeliveryNotificationOptions (which allows you to be notified when the recipient receives an email). The notification types available are:

  • OnSuccess (Notify if the delivery is successful)
  • OnFailure (Notify if the delivery is unsuccessful)
  • Delay (Notify if the delivery is delayed)

You can specify multiple options in one command:

Send-MailMessage … -DeliveryNotificationsOptions 'OnSuccess', 'OnFailure'

The delivery notification will be sent to the mailbox that is specified in the “From” field.

You can also set the priority of the email message (not shown in some clients):

-Priority High|Low|Normal

If you want to add an attachment to your email, use the -Attachments option. In the example below, we are going to send an e-mail in the HTML format (-BodyAsHtml) and attach file1.txt and report.xsls from the local drive.

$MailMessage = @{
To = "[email protected]"
Bcc = "[email protected]", "[email protected]"
From = "DC server <[email protected]>"
Subject = "DC Server Report"
Body = "<h1>Welcome!</h1> <p><strong>Generated:</strong> $(Get-Date -Format g)</p>”
Smtpserver = "smtp.gmail.com"
Port = 587
UseSsl = $true
BodyAsHtml = $true
Encoding = “UTF8”
Attachment = “C:\Logs\file1.txt”, “C:\Logs\report.xlsx”
}
Send-MailMessage @MailMessage -Credential $cred

In this example, we have also replaced the recipient’s display name with “DC server”.

Here is how the HTML email with attachments looks in the Gmail interface.

a test email with an attachment generated with PowerShell in the Gmail interface

When you send an email on behalf of an Exchange/Microsoft 365 shared mailbox for which you’ve been granted SendAs permissions, you can specify that a copy of the message should be saved in the Sent Items folder of the source mailbox. For that, enable the MessageCopyForSentAsEnabled parameter for the mailbox:

Set-Mailbox it_dept -MessageCopyForSentAsEnabled $True

Using Send-MailMessage with SMTP Auth and TLS/SSL

By default, the Send-MailMessage cmdlet sends an e-mail via the default unencrypted SMTP port TCP 25. If your SMTP server allows sending e-mail only using an encrypted protocol, you can specify the port number in the -Port attribute (most often it is 465 or 587) and the –UseSsl option:

-SmtpServer 'smtp.woshub.com' -Port 465 –UseSsl

An error will occur if the SMTP server’s SSL certificate doesn’t match the FQDN specified in the HELO:

Send-MailMessage: The remote certificate is invalid according to the validation procedure.

You may also receive an error when sending an email using SSL/TLS encryption:

Send-MailMessage : Unable to read data from the transport connection: net_io_connectionclosed

In this case, it is recommended that you check the following

  • That the specified SMTP port is open and accessible from your computer: Test-NetConnection smtp.woshub.com –Port 465
  • Try a different SMTP port. For example, 587 (msa) instead of 465 (smtps). Port 587 is the default when using the STARTTLS extension;
  • If you are using an older operating system (Windows Server 2012/Windows 8 and below), you must enable TLS 1.2 protocol support for PowerShell by using the command:
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
The table below lists the SMTP server settings for the popular public e-mail providers that you can use to send messages from PowerShell (note that you must allow e-mail to be sent via SMTP in the account interface.):

NameSMTP Server AddressPortEncryption Type
Gmailsmtp.gmail.com587

25

465

TLS

TLS

SSL

Microsoft (Office) 365smtp.office365.com587TLS
Outlook.comsmtp-mail.outlook.com587TLS
Yahoosmtp.mail.yahoo.com587TLS
iCloud mailsmtp.mail.me.com587TLS
AOL smtp.aol.com465SSL

If the SMTP server doesn’t allow anonymous email (relay is denied), you will see this error:

5.7.1 Client was not authenticated.

or:

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM.

Then you can authenticate to the SMTP server using the -Credential option.

You can interactively prompt for the user’s credentials for authentication:

Send-MailMessage …… -Credential (Get-Credential)

Send Authenticated SMTP with PowerShell Send-MailMessage

You can also specify the account credentials to use for authentication in the variable:

$cred = Get-Credential
Send-MailMessage ... -Credential $cred

How to Send an Email via the Gmail SMTP with PowerShell?

To send an email from your mailbox on one of the public mail services, it is recommended that you use an App Password instead of a password to access your account/mailbox. For example, in Gmail, you can create an app password after you enable the two-factor authentication for your Google Account. Generate and copy your app password on Google (it’s a 16-character password).

generate smtp app password in gmail

The following example shows how to send an email from your Google mailbox using PowerShell. You must use the App Password instead of your Google account password. In this example, we will specify the app password for connecting to the Gmail SMTP server directly in the PowerShell script code.

$From = "[email protected]"
$To = "[email protected]"
$Subject = "Test PowerShell email from $($env:computername)"
$Body = "some message test "
$Password = "your_google_app_password" | ConvertTo-SecureString -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $From, $Password
Send-MailMessage -From $From -To $To -Subject $Subject -Body $Body -SmtpServer "smtp.gmail.com" -port 587 -UseSsl -Credential $Credential

Note that PowerShell saves the command with the plain-text password in the PowerShell command history file.

A warning is displayed when you use the Send-MailMessage command in new versions of PowerShell Core 7.x:

WARNING: The command 'Send-MailMessage' is obsolete. This cmdlet does not guarantee secure connections to SMTP servers. While there is no immediate replacement available in PowerShell, we recommend you do not use Send-MailMessage at this time. See https://aka.ms/SendMailMessage for more information.

powershell command send-mailmessage is obsolete

The Send-MailMessage cmdlet uses the .NET SmtpClient class that doesn’t support modern authentication methods, including Microsoft Modern Authentication. It is recommended that you use the Graph API to send emails from PowerShell through the Microsoft 365/Exchange Online (by using the Send-MgUserMail cmdlet or Invoke-RestMethod to call the sendMail method via the REST API).

8 comments
8
Facebook Twitter Google + Pinterest
previous post
Clear Cache and Temp Files in User Profiles on Windows (RDS) with PowerShell and GPO
next post
Fix: Remote Desktop Services Is Currently Busy

Related Reading

Map a Network Drive over SSH (SSHFS) in...

May 13, 2025

How to Cancel Windows Update Pending Restart Loop

May 6, 2025

View Windows Update History with PowerShell (CMD)

April 30, 2025

Change BIOS from Legacy to UEFI without Reinstalling...

April 21, 2025

Remove ‘Your License isn’t Genuine’ Banner in MS...

April 21, 2025

8 comments

shafic January 26, 2022 - 7:43 pm

Thanks a lot. i get clarity on this page even gothrough same query on multiple site

Reply
Adam August 11, 2022 - 11:55 pm

There is a much simpler way to send email from the command line:
https://sourceforge.net/projects/mail-alert/

Reply
steve December 20, 2022 - 9:33 pm

Simpler? Questionable.
An executable from “adam” in a corporate environment? Unlikely.

Reply
federico April 17, 2023 - 3:36 pm

Salve due richieste :
-c’è un modo per far si che una volta che l’utente si è loggato o ha fatto il logoff ma per ipotesi ci fosse assenza di rete e quindi no internet, il sistema provi a inviare lo stesso l’email ma non trovando modo di inviarla perchè internet assente la tenga in coda finche la connessione non viene ripristinata anche per esempio il giorno successivo?
-quando spengo il pc non fa in tempo a mandare l’email perchè il sistema disconnette subito la rete ,come si puo’ fare per far si che windows non disabiliti la rete allo spegnimento finche prima non è stata inviata l’email?

Grazie

Reply
federico April 17, 2023 - 3:37 pm

Hi, two requests:
-is there a way to ensure that once the user is logged in or has logged off but hypothetically there was no network and therefore no internet, the system tries to send the email anyway but cannot find way to send it because the internet is absent keep it in the queue until the connection is restored also for example the next day?
-when I turn off the pc it doesn’t have time to send the email because the system immediately disconnects the network, how can you do to ensure that windows does not disable the network on shutdown until the email has been sent first?

Thank you

Reply
Carlos Kassab May 13, 2024 - 9:35 pm

How can I make PowerShell stopping asking for the password?, I need my process to run in a job.

Thank you in advance

Reply
Adam May 14, 2024 - 6:08 pm

Just use command line tool Mail Alert Simple Mailer (https://sourceforge.net/projects/mail-alert/) and forget about password prompts. Your mail server password will be stored in encrypted form, so it is much safer solution then PowerShell script.

Reply
admin May 21, 2024 - 12:05 pm

You can pass the credential object directly to the Send-MailMessage command:

Send-MailMessage ..... -credential (new-object System.Net.NetworkCredential("user1","pass1","domain"))'

Reply

Leave a Comment Cancel Reply

join us telegram channel https://t.me/woshub
Join WindowsHub Telegram channel to get the latest updates!

Categories

  • Active Directory
  • Group Policies
  • Exchange Server
  • Microsoft 365
  • Azure
  • Windows 11
  • Windows 10
  • Windows Server 2022
  • Windows Server 2019
  • Windows Server 2016
  • PowerShell
  • VMware
  • Hyper-V
  • Linux
  • MS Office

Recent Posts

  • Cannot Install Network Adapter Drivers on Windows Server

    April 29, 2025
  • Change BIOS from Legacy to UEFI without Reinstalling Windows

    April 21, 2025
  • How to Prefer IPv4 over IPv6 in Windows Networks

    April 9, 2025
  • Load Drivers from WinPE or Recovery CMD

    March 26, 2025
  • How to Block Common (Weak) Passwords in Active Directory

    March 25, 2025
  • Fix: The referenced assembly could not be found error (0x80073701) on Windows

    March 17, 2025
  • Exclude a Specific User or Computer from Group Policy

    March 12, 2025
  • AD Domain Join: Computer Account Re-use Blocked

    March 11, 2025
  • How to Write Logs to the Windows Event Viewer from PowerShell/CMD

    March 3, 2025
  • How to Hide (Block) a Specific Windows Update

    February 25, 2025

Follow us

  • Facebook
  • Twitter
  • Telegram
Popular Posts
  • Install and Manage Windows Updates with PowerShell (PSWindowsUpdate)
  • Fix: Remote Desktop Licensing Mode is not Configured
  • How to Delete Old User Profiles in Windows
  • Configuring Port Forwarding in Windows
  • How to Install Remote Server Administration Tools (RSAT) on Windows
  • Start Menu or Taskbar Search Not Working in Windows 10/11
  • Adding Drivers into VMWare ESXi Installation Image
Footer Logo

@2014 - 2024 - Windows OS Hub. All about operating systems for sysadmins


Back To Top