How to Send Emails in PowerShell using Send-MailMessage? (2024)

How to Send Emails in PowerShell using Send-MailMessage? (1)

Email is an essential communication tool used in most organizations. As a system administrator, you may need to send emails directly from PowerShell scripts to automate notifications or reports. With PowerShell, you can send emails from command-line scripts, automate email notifications, and even integrate email functionality into your larger automation workflows. This comprehensive guide will explore various techniques and approaches for sending emails from PowerShell.

We will cover the benefits of each approach, the basics of the Send-MailMessage command, how to send emails using Office 365 credentials, how to send emails from any SMTP server like your On-premises Exchange server, Gmail, and more. By the end of this article, you will have the knowledge and skills needed to master the art of sending emails from PowerShell.

Table of contents

  • Benefits of using PowerShell for sending email
  • Understanding the PowerShell Send-MailMessage cmdlet
  • Sending basic emails from PowerShell – Example
  • Sending SMTP email from PowerShell
  • How to send an email using PowerShell with Office 365?
  • Sending Emails from MFA-Enabled Microsoft 365 Accounts
  • Add Attachments to the Email in PowerShell
  • Sending Email with Saved Credentials in PowerShell
  • How to send email to multiple recipients in PowerShell?
  • Sending HTML emails from PowerShell
  • Sending email using PowerShell with Azure
  • Other available Methods to send Email with PowerShell
    • Method 1: Sending Mail using SMTP and .Net Methods in PowerShell
    • Method 2: The Send-PnPMail cmdlet from the PnP PowerShell Module
    • Method 3: Sending an email using PowerShell with Outlook
    • Method 4: Sending an email using PowerShell with Exchange Server
    • Method 5: Send Email with Send-MGUserMail cmdlet in Microsoft Graph
  • Troubleshooting Common Issues
  • Wrapping up

Benefits of using PowerShell for sending email

Before delving into the technical details, it’s important to understand why PowerShell is an ideal choice for sending emails. One of the key advantages is its seamless integration with the Windows operating system. PowerShell comes pre-installed on all modern versions of Windows, making it readily accessible without additional software installation.

Sending emails from PowerShell offers several benefits. First, it allows you to automate email-based tasks. For example, you can use PowerShell to send daily reports or notifications to your team. With its extensive cmdlets and scripting capabilities, PowerShell enables you to automate complex tasks and send emails easily, whether a simple notification or a more sophisticated message containing attachments or HTML content.

Second, it provides a streamlined and consistent approach to email communication. By using PowerShell, you can ensure that your emails are formatted and structured consistently.

Third, it can save you time. Instead of manually composing and sending emails, you can use PowerShell to automate the process. Furthermore, PowerShell’s integration with various email protocols and services, such as SMTP, Office 365, Outlook, Azure, Exchange, and Gmail, allows you the flexibility to send emails through different platforms, depending on your specific requirements.

Here are some common scenarios where sending email from PowerShell is useful:

  • Send alerts and notifications from your scripts
  • Automatically generate and email reports
  • Forward monitoring data and logs to your inbox
  • Integrate systems and workflows with email notifications
  • Avoid logging into an SMTP server to send automated mail
  • Script anything you can do via Outlook from the command line

Overall, email capabilities make PowerShell much more helpful for real-world tasks.

Understanding the PowerShell Send-MailMessage cmdlet

At the core of sending emails from PowerShell lies the Send-MailMessage cmdlet. This versatile cmdlet provides a straightforward way to send emails using a single command. By understanding its parameters and capabilities, you can unlock the full potential of PowerShell for sending emails.

The Send-MailMessage cmdlet lets you specify the sender and recipient email addresses, subject, body, and even attachments. You can send plain text emails or format them as HTML, providing rich content to your recipients. Additionally, the cmdlet supports various authentication methods, enabling you to send emails securely and reliably.

Here is the basic syntax for using Send-MailMessage command:

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>]

Let’s break down this command. Here’s a table that outlines the parameters for the Send-MailMessage cmdlet in PowerShell:

ParameterDescription
-AttachmentsSpecifies the path and file names of files to be attached to the email.
-BccSpecifies the email addresses to receive the copy of the mail (blind carbon copy) field. But not listed as recipients of the message.
-BodyThe value of the Body parameter sets the content of the email message.
-BodyAsHtmlSpecifies the delivery notifications that you want the SMTP server to send to the message sender.
-CcSpecifies the email addresses that you want to include in the “Cc” (carbon copy) field.
-CredentialSpecifies a user account that has permission to send the email. The default is the current user.
-DeliveryNotificationOptionSpecifies the delivery notification options you want the SMTP server to send to the message sender. Aliases: dno. The DeliveryNotificationOption parameter specifies two values, OnSuccess and OnFailure.
-EncodingSpecifies the character encoding such as Unicode, UTF-16, ASCII, OEM used for the email message.
-FromSpecifies the email address that the email message is sent from.
-PriorityThe Priority parameter sets the message priority of the email message to High, Normal, or Low.
-SmtpServerThe SmtpServer parameter specifies the name of the SMTP server that sends the email message.
-SubjectSpecifies the subject of the email message.
-ToSpecifies the email addresses of the recipients of the email message.
-UseSslDirects the cmdlet to use Secure Socket Layer to establish the connection to the remote computer.
-PortSpecifies the port to use when you connect to the SMTP server. The default value is 25
-ReplyToSpecifies the email addresses for the “Reply-To” field in the email message.

In the upcoming sections of this guide, we will explore the Send-MailMessage cmdlet in-depth, along with its various usage scenarios.

Sending basic emails from PowerShell – Example

Sending basic emails from PowerShell is a straightforward process that involves using the Send-MailMessage cmdlet with the essential parameters. To send a basic email, you need to specify the recipient’s email address, the subject, and the body of the email.

Here’s an example of sending a basic email from PowerShell:

#Config Variables$Recipient = "Salaudeen@Crescent.com"$Subject = "Hello, World!"$Body = "This is the body of the email."$credentials = Get-CredentialSend-MailMessage -To $Recipient -Subject $subject -Body $body -From $credentials.UserName -SmtpServer "smtp.office365.com" -Port 587 -UseSsl -Credential $credentials

In this example, we set the recipient’s email address using the -To parameter, the sender’s email address using the -From parameter, the subject using the -Subject parameter, and the body of the email using the -Body parameter. You can omit the “-Credential” parameter, if your server/Pc’s IP address is added under “Allowed IPs” in the SMTP server, or if you have the Inbound connector created in the Exchange server.

You will send a basic email to the specified recipient by running this command in PowerShell. This simple, yet powerful capability allows you to automate sending routine emails, such as notifications or status updates.

Sending SMTP email from PowerShell

SMTP (Simple Mail Transfer Protocol) is a standard protocol used for sending emails over the Internet. PowerShell provides native support for sending SMTP email, allowing you to leverage this widely adopted protocol for your email communication.

To send SMTP email from PowerShell, you need to specify the SMTP server address and port using the -SmtpServer and -SmtpPort parameters, respectively. Additionally, you may need to provide authentication credentials and other optional parameters, depending on your specific SMTP server configuration.

Here’s an example of sending SMTP email from PowerShell:

$smtpServer = "smtp.crescent.com"$smtpPort = 587 #Default smtp port$smtpUsername = "user@crescent.com"$smtpPassword = ConvertTo-SecureString -String "password" -AsPlainText -Force$smtpCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $smtpUsername, $smtpPasswordSend-MailMessage -To "recipient@crescent.com" -From "sender@crescent.com" -Subject "SMTP email" -Body "This email is sent using SMTP from PowerShell." -SmtpServer $smtpServer -SmtpPort $smtpPort -Credential $smtpCredential

In this example, we set the SMTP server address and port using the -SmtpServer and -SmtpPort parameters. We create a PSCredential object containing the SMTP username and password, and then provide it as the value for the -Credential parameter.

Configuring the appropriate SMTP server details and authentication credentials allows you to send SMTP email from PowerShell, ensuring reliable and efficient email delivery.

You can expand this into a reusable function:

Function Send-Email { Param( [String]$To, [String]$From, [String]$Subject, [String]$Body, [String]$Server = "smtp.Crescent.com", [String]$Attachment ) Send-MailMessage -To $To -From $From -Subject $Subject ` -Body $Body -SmtpServer $Server -Attachments $Attachment}#Call the function Send-EMail -To "ITMgr@Crescent.com" -From "admin@Crescent.com" -Subject "Report" -Body "See attached report" -SmtpServer "smtp.crescent.com" -Attachments "C:\Reports\report.pdf"

This sends an email to the mailing list ITMgr@Crescent.com from admin@Crescent.com using the SMTP server at smtp.Crescent.com.

SMTP Authentication

If you need to send email using SMTP authentication, provide the -Credential parameter with a PSCredential object:

$username = "jsmith@Crescent.com"$password = ConvertTo-SecureString -String "P@ssword1" -AsPlainText -Force$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $passwordSend-MailMessage -To "admin@Crescent.com" -From "jsmith@Crescent.com" -Subject "Report" -Body "See attached report" -SmtpServer "smtp.Crescent.com" -Attachments "C:\Reports\report.pdf" -Credential $cred 

This allows sending mail via SMTP servers that require authentication.

How to send an email using PowerShell with Office 365?

Office 365 is a popular cloud-based productivity suite that includes email services. PowerShell provides seamless integration with Office 365, enabling you to send emails using your Office 365 account. To send email using PowerShell with Office 365, you need to specify the Office 365 SMTP server address and port using the -SmtpServer and -SmtpPort parameters, respectively. You must also provide your Office 365 email address and password as authentication credentials.

Pre-requisites: You must enable the SMTP protocol for your tenant to be able to send Emails in Office 365. How to Enable SMTP Protocol in Microsoft 365 Exchange Online Admin Center?

Here is the PowerShell script to send email in from Microsoft 365 Exchange Online:

#Get Microsoft 365 Account Credentials to send Email$Credential = Get-Credential#Define Email Parameters$EmailParams = @{ From = "sender@Crescent.com" To = "recipient@Crescent.com" Subject = "Test Email" Body = "This is a test email sent using PowerShell in Office 365." SmtpServer = "smtp.office365.com" Port = 587 UseSsl = $true Credential = $Credential }#Send EmailSend-MailMessage @EmailParams

Provide -Credential of your Office 365 account authentication. Here’s another example of sending email using PowerShell in Office 365 with saved credentials:

$smtpServer = "smtp.office365.com"$smtpPort = 587$smtpUsername = "user@Crescent.com"$smtpPassword = ConvertTo-SecureString -String "password" -AsPlainText -Force$smtpCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $smtpUsername, $smtpPasswordSend-MailMessage -To "recipient@Crescent.com" -From "sender@Crescent.com" -Subject "Office 365 email" -Body "This email is sent using PowerShell with Office 365." -SmtpServer $smtpServer -SmtpPort $smtpPort -Credential $smtpCredential

In this example, we set the Office 365 SMTP server address and port to “smtp.office365.com” and 587, respectively. We create a PSCredential object containing the Office 365 email address and password, and then provide it as the value for the -Credential parameter.

By utilizing the appropriate SMTP server details and Office 365 authentication credentials, you can send emails from PowerShell with Office 365, leveraging the power of the cloud for your email communication.

Sending email without credentials using PowerShell

Sometimes, you may need to send emails without using credentials, especially if you’re running the script in an unattended mode or from a scheduled task. In such cases, you can use the Send-MailMessage cmdlet directly, without establishing a connection to the Exchange Online service. To send an email without credentials using PowerShell Office 365, You need to have one of the following:

  1. Anonymous SMTP session: This method involves addressing the Office 365 mail infrastructure without providing any credentials. This can be useful for testing or automation purposes, such as sending a daily report.
  2. Direct Send: This method involves sending email via SMTP Client Submission or SMTP Authenticated Submission. Using PowerShell’s Send-MailMessage cmdlet, we can send emails without providing credentials. However, this method requires that the sender’s IP address is added to the Office 365 Direct Send IP Address list.

Here’s an example script that demonstrates how to send an email in Office 365 without credentials using PowerShell:

$EmailParams = @{ From = "sender@Crescent.com" To = "recipient@Crescent.com" Subject = "Test Email" Body = "This is a test email sent using PowerShell in Office 365." SmtpServer = "smtp.office365.com" Port = 587 UseSsl = $true}Send-MailMessage @EmailParams

This script defines the email parameters directly in the $EmailParams hashtable, including the sender, recipient, subject, body, SMTP server, port, and SSL settings. The Send-MailMessage cmdlet is then used to send the email with the specified parameters.

It’s important to note that when sending email without credentials, the SMTP server must allow anonymous access or have the necessary permissions configured.

Sending Emails from MFA-Enabled Microsoft 365 Accounts

Sending emails from an MFA-enabled (Multi-Factor Authentication) Office 365 account using PowerShell requires a bit of preparation because traditional methods that rely on basic authentication won’t work. One way to work with MFA-enabled accounts is to use App Password (You need 2FA enabled to get the App Password option) or leverage the Microsoft Graph API.

#Setup User name and Password$UserName = "Steve@Crescent.com"$Password = "lcapqfbfhhraqbqnxfzgs"$SecurePassword = ConvertTo-SecureString -string $password -AsPlainText -Force$Cred = New-Object System.Management.Automation.PSCredential -argumentlist $UserName, $SecurePasswordSend-MailMessage -To "Salaudeen@Crescent.com" -From "steve@Crescent.com" -Subject "Hello from PowerShell" -Body "This is a test email sent from PowerShell." -SmtpServer "smtp.office365.com" -Port 587 -UseSSL -Credential $Cred

Add Attachments to the Email in PowerShell

In numerous instances, you may need to send emails with attachments, such as documents, images, or other files. PowerShell provides a convenient way to accomplish this by utilizing the -Attachments parameter of the Send-MailMessage cmdlet.

To send an email with attachments from PowerShell, you need to specify the file paths of the attachments as values for the -Attachments parameter. You can provide multiple file paths by separating them with commas.

Here’s an example of sending an email with attachments from PowerShell:

Send-MailMessage -To "recipient@Crescent.com" -From "sender@Crescent.com" -Subject "Email with attachments" -Body "Please find the attached files." -Attachments "C:\Documents\File1.docx", "C:\Images\Picture1.jpg" -Priority High

In this example, we include file names of attachments: “File1.docx” located in the “C:\Documents” folder and “Picture1.jpg” located in the “C:\Images” folder. By running this command, you will send the recipient an email with the specified attachments.

#Setup User name and Password$UserName = "steve@Crescent.com"$Password = "lcpqffshhrqdbqanfzxg"$SecurePassword = ConvertTo-SecureString -string $password -AsPlainText -Force$Cred = New-Object System.Management.Automation.PSCredential -argumentlist $UserName, $SecurePasswordSend-MailMessage -To "Salaudeen@Crescent.com" -From "steve@Crescent.com" -Subject "Hello from PowerShell" -Body "This is a test email sent from PowerShell." -SmtpServer "smtp.office365.com" -Port 587 -UseSSL -Credential $Cred -Attachments "C:\Reports\PermissionReport.csv"

Sending emails with attachments from PowerShell allows you to automate the process of sharing files via email, saving time and effort in manual file attachment tasks.

Here is a cleaner way:

#Setup Credentials$UserName = "steve@Crescent.com"$Password = "slcapqffhhrcqbqanfzgx"$SecurePassword = ConvertTo-SecureString -string $password -AsPlainText -Force$Cred = New-Object System.Management.Automation.PSCredential -argumentlist $UserName, $SecurePassword#Set Parameters for the Email$EmailParams = @{ From = "steve@Crescent.com" To = "Salaudeen@Crescent.com" Subject = "Permission Report" Body = "Please find the attached Reports" SmtpServer = "smtp.office365.com" Port = 587 UseSsl = $true Credential = $Cred Attachments = "C:\Reports\PermissionReport.csv", "C:\Reports\UsersReport.csv"}#Call the Send-MailMessage to Send EmailSend-MailMessage @EmailParams

Sending Email with Saved Credentials in PowerShell

To ensure the security and reliability of email communication, it’s often necessary to send authenticated emails. PowerShell provides support for various authentication methods, such as username and password, SSL/TLS encryption, and OAuth, allowing you to send authenticated emails with ease.

To send authenticated email using PowerShell, you need to specify the appropriate authentication parameters when invoking the Send-MailMessage cmdlet. The specific parameters depend on the authentication method you choose.

For example, to send an email using username and password authentication, you can use the -Credential parameter and provide a PSCredential object containing the username and password. Here’s an example:

$smtpServer = "smtp.Crescent.com"$smtpPort = 587$smtpUsername = "user@Crescent.com"$smtpPassword = ConvertTo-SecureString -String "password" -AsPlainText -Force$smtpCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $smtpUsername, $smtpPasswordSend-MailMessage -To "recipient@Crescent.com" -From "sender@Crescent.com" -Subject "Authenticated email" -Body "This is an authenticated email sent from PowerShell." -SmtpServer $smtpServer -SmtpPort $smtpPort -Credential $smtpCredential

In this example, we specify the SMTP server address and port using the -SmtpServer and -SmtpPort parameters, respectively. We create a PSCredential object containing the SMTP username and password, and then provide it as the value for the -Credential parameter.

Using the appropriate authentication parameters, you can send authenticated emails from PowerShell, ensuring secure and trustworthy communication.

How to send email to multiple recipients in PowerShell?

There are scenarios where you may need to simultaneously send emails to multiple recipients. PowerShell allows you to achieve this by utilizing the -To parameter with multiple email addresses separated by commas.

Here’s an example of sending an email to multiple recipients from PowerShell:

Send-MailMessage -To "recipient1@Crescent.com", "recipient2@Crescent.com", "recipient3@Crescent.com" -From "sender@Crescent.com" -Subject "Email to multiple recipients" -Body "This email is sent to multiple recipients."

In this example, we provide multiple email addresses as values for the -To parameter, separated by commas. By running this command, you will email all the specified recipients.

To email multiple recipients, pass an array of addresses to the -To parameter:

$Recipients = @("jsmith@contoso.com", "admin@contoso.com")Send-MailMessage -To $Recipients -From "reports@contoso.com" -Subject "Daily Report" -Body "See attached report" -SmtpServer "smtp.contoso.com" -Attachments "C:\Reports\report.pdf"

By leveraging this capability, you can automate the process of sending emails to multiple recipients, simplifying communication and saving valuable time.

Sending email to multiple recipients from a CSV file using PowerShell

Sending emails to multiple recipients manually can be time-consuming and error-prone. PowerShell allows you to automate this process by reading recipient information from a CSV file and sending emails to each recipient.

To send email to multiple recipients from a CSV file using PowerShell, you must first import the CSV file and iterate through each row to extract the recipient information. You can then use the Send-MailMessage cmdlet to send individual emails to each recipient.

Here’s an example script that demonstrates how to send email to multiple recipients from a CSV file using PowerShell:

$UserCredential = Get-Credential$Recipients = Import-Csv -Path "recipients.csv"foreach ($Recipient in $Recipients) { $EmailParams = @{ From = "sender@Crescent.com" To = $Recipient.Email Subject = "Test Email" Body = "This is a test email sent using PowerShell in Office 365." SmtpServer = "smtp.office365.com" Port = 587 UseSsl = $true Credential = $UserCredential } Send-MailMessage @EmailParams}

In this script, we first prompt the user to enter their Office 365 credentials using the Get-Credential cmdlet. The Import-Csv cmdlet is used to import the recipient information from the “recipients.csv” file.

We then iterate through each recipient using a foreach loop and define the email parameters, including the sender, recipient, subject, body, SMTP server, port, SSL settings, and credentials. The Send-MailMessage cmdlet is used to send an email to each recipient with the specified parameters.

Sending HTML emails from PowerShell

While plain text emails serve their purpose, there are scenarios where you may need to send emails with rich content, such as formatted text, images, or hyperlinks. PowerShell allows you to send HTML emails, providing a flexible and visually appealing way to communicate with your recipients. By default, all emails sent through PowerShell are plain text. To send rich HTML content, specify the BodyAsHtml parameter:

To send HTML emails from PowerShell, you need to specify the body of the email as HTML content. You can do this by utilizing the -BodyAsHtml parameter of the Send-MailMessage cmdlet and providing the HTML content as the value for the -Body parameter.

Here’s an example of sending an HTML email from PowerShell:

#Setup Credentials$UserName = "steve@Crescent.com"$Password = "lcpq2ffhhrqxabqnbfzg"$SecurePassword = ConvertTo-SecureString -string $password -AsPlainText -Force$Cred = New-Object System.Management.Automation.PSCredential -argumentlist $UserName, $SecurePassword$htmlBody = @"<html><body><h1>This is an HTML email</h1><p>This email is sent from PowerShell.</p><p>Here's a <a href="https://Crescent.com">link</a> for reference.</p></body></html>"@#Set Parameters for the Email$EmailParams = @{ From = "steve@Crescent.com" To = "Salaudeen@Crescent.com" Subject = "Permission Report" Body = $htmlBody SmtpServer = "smtp.office365.com" Port = 587 UseSsl = $true Credential = $Cred cc = "steve@Crescent.com" bcc = "sales@Crescent.com" BodyAsHtml = $True}#Call the Send-MailMessage to Send EmailSend-MailMessage @EmailParams

In this example, we define the HTML content.

Using BCC and CC in the email from PowerShell

When sending emails from PowerShell, it is often necessary to include multiple recipients or send a blind carbon copy (BCC) or carbon copy (CC) to additional recipients. PowerShell provides options to include BCC and CC recipients in your emails.

To include BCC and CC recipients in your email, you can use the -Bcc and -Cc parameters of the Send-MailMessage cmdlet. These parameters accept an array of email addresses.

Here is an example of how to include BCC and CC recipients in an email:

#Setup Credentials$UserName = "Steve@Crescent.com"$Password = "lcpaqffhhgrsqb2qnfazag"$SecurePassword = ConvertTo-SecureString -string $password -AsPlainText -Force$Cred = New-Object System.Management.Automation.PSCredential -argumentlist $UserName, $SecurePassword#Set Parameters for the Email$EmailParams = @{ From = "steve@Crescent.com" To = "Salaudeen@Crescent.com" Subject = "Permission Report" Body = "This is a test email sent using PowerShell in Office 365." SmtpServer = "smtp.office365.com" Port = 587 UseSsl = $true Credential = $Cred cc = "steve@Crescent.com" bcc = "sales@Crescent.com"}Send-MailMessage @EmailParams

In the above example, we specify the primary recipient using the -To parameter. We then include a CC recipient using the -Cc parameter and a BCC recipient using the -Bcc parameter. Finally, we use the Send-MailMessage cmdlet to send the email, including the primary recipient, CC recipient, BCC recipient, and the SMTP server.

Sending email using PowerShell with Azure

Azure is a cloud computing platform that provides a wide range of services, including email functionalities. PowerShell allows you to send emails using Azure, leveraging its robust infrastructure and seamless integration with other Azure services.

To send email using PowerShell with Azure, you need to utilize the Azure SMTP relay service. This service enables you to send emails using a secure and reliable SMTP server provided by Azure.

Here’s an example of sending email using PowerShell with Azure:

$smtpServer = "smtp.sendgrid.net"$smtpPort = 587$smtpUsername = "azure_1234567890@azure.com"$smtpPassword = ConvertTo-SecureString -String "password" -AsPlainText -Force$smtpCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $smtpUsername, $smtpPasswordSend-MailMessage -To "recipient@Crescent.com" -From "sender@Crescent.com" -Subject "Azure email" -Body "This email is sent using PowerShell with Azure." -SmtpServer $smtpServer -SmtpPort $smtpPort -Credential $smtpCredential

In this example, we set the Azure SMTP server address to “smtp.sendgrid.net” and the port to 587. We create a PSCredential object containing the Azure username and password, and then provide it as the value for the -Credential parameter.

By utilizing the appropriate Azure SMTP server details and authentication credentials, you can send emails from PowerShell with Azure, harnessing the power of the cloud for your email communication.

PowerShell to Send email via Gmail

In addition to Exchange, PowerShell can also be used to send emails using Gmail. This can be useful if you need to send emails from a personal Google account or if your organization uses Gmail as its email provider.

To send an email using PowerShell and Gmail, you will need to create an App Password in your Gmail account 2FA settings. This allows PowerShell to authenticate with Gmail using your email address and password. If the App Password is not set, You’ll get the error:

“Send-MailMessage : The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required.”

Once you created an App Password, you can use the Send-MailMessage cmdlet to send an email. Here is an example:

# SMTP server information$smtpServer = "smtp.gmail.com"$smtpPort = 587# Email details$smtpFrom = "Salaudeen@gmail.com"$smtpTo = "Monitoring.Rpt1@gmail.com"$subject = "Your Subject Here"$body = "Your email body content here."#Setup User name and Password$UserName = "Salaudeen.@gmail.com"$Password = "xxxx xxxx xxxx xxxx" #Insert your App Password here$SecurePassword = ConvertTo-SecureString -string $password -AsPlainText -Force$Cred = New-Object System.Management.Automation.PSCredential -argumentlist $UserName, $SecurePassword# Send email from GmailSend-MailMessage -SmtpServer $smtpServer -Port $smtpPort -UseSsl -Credential $Cred -From $smtpFrom -To $smtpTo -Subject $subject -Body $Body

In the above example, we specify the recipient, subject, and body of the email. We then prompt the user for their Gmail credentials using the Get-Credential cmdlet. Finally, we use the Send-MailMessage cmdlet to send the email, specifying the recipient, subject, body, SMTP server, port, SSL, and the provided credentials.

Other available Methods to send Email with PowerShell

Apart from the Send-MailMessage cmdlet, there are other ways you can utilize to trigger Emails via PowerShell.

Method 1: Sending Mail using SMTP and .Net Methods in PowerShell

Sending mail using the .NET methods in PowerShell is achieved mainly through the System.Net.Mail.SmtpClient and System.Net.Mail.MailMessage classes. Here’s a step-by-step process to send an email using .NET methods:

# Create a new MailMessage object$message = New-Object System.Net.Mail.MailMessage$message.From = "sender@Crescent.com"$message.To.Add("recipient@Crescent.com")$message.Subject = "Test Email using .NET in PowerShell"$message.Body = "This is a test email sent using .NET methods in PowerShell."# Create a new SmtpClient object$smtpClient = New-Object System.Net.Mail.SmtpClient$smtpClient.Host = "smtp.Crescent.com"$smtpClient.Port = 587$smtpClient.EnableSsl = $true$smtpClient.Credentials = New-Object System.Net.NetworkCredential("sender@Crescent.com", "password")# Send the email$smtpClient.Send($message)

Method 2: The Send-PnPMail cmdlet from the PnP PowerShell Module

The Send-PnPMail is a cmdlet from the SharePoint PnP (Patterns and Practices) PowerShell module, that allows users and administrators to manage SharePoint sites and Office 365 environment. While PnP is primarily associated with SharePoint and Microsoft 365 tasks, it also offers a set of utilities for other purposes, and one of them is the capability to send emails.

Send-PnPMail -To "recipient@Crescent.com" -Subject "Test PnP Mail" -Body "Hello, this is a test email from PnP PowerShell."

Here is another article for sending emails with the Send-PnPMail cmdlet: How to Send Email from PowerShell for SharePoint Online?

Method 3: Sending an email using PowerShell with Outlook

Outlook is a widely used email client that integrates seamlessly with the Microsoft Office suite. PowerShell allows you to send emails using your Outlook account, providing a convenient way to automate email communication within your organization.

To send email using PowerShell with Outlook, you need to have Outlook installed on your machine. PowerShell utilizes the Outlook COM (Component Object Model) interface to interact with Outlook.

Here’s an example of sending email using PowerShell with Outlook:

$outlook = New-Object -ComObject Outlook.Application# Create a new mail item$mailItem = $outlook.CreateItem(0)# Set the recipient, subject, and body of the email$mailItem.To = "steve@Crescent.com"$mailItem.Subject = "Email from PowerShell with Outlook"$mailItem.Body = "This email is sent using PowerShell with Outlook."# Send the email$mailItem.Send()

In this example, we create an Outlook application object using the New-Object cmdlet. We then create a new mail item using the CreateItem method of the Outlook application object. We set the recipient, subject, and body of the email using the appropriate properties of the mail item. Finally, we call the Send method to send the email.

By utilizing the Outlook COM interface, you can send emails from PowerShell with Outlook, automating your email communication within the familiar Outlook environment.

Method 4: Sending an email using PowerShell with Exchange Server

PowerShell is a powerful scripting language that allows system administrators to automate various tasks, including sending emails. This section will explore how to send emails using PowerShell with Exchange.

You must establish a connection to your Exchange server to send an email using PowerShell and Exchange.

Here is an example of how to send an email using PowerShell with Exchange:

# Define email parameters$EmailParameters = @{ SmtpServer = "your.exchange.server.com" # Exchange Server address Port = 25 # SMTP port (default is 25 for non-SSL, 587 for SSL) From = "sender@Crescent.com" To = "recipient@Crescent.com" Subject = "Test Email from PowerShell with Exchange" Body = "This is a test email sent from PowerShell via an Exchange Server." Credential = Get-Credential # Prompt for credentials # UseSsl = $true # Uncomment this if using SSL}# Send the emailSend-MailMessage @EmailParameters

In the above example, we first prompt the user for their credentials using the Get-Credential cmdlet. We then specify the recipient, subject, and body of the email. Finally, we use the Send-MailMessage cmdlet to send the email, specifying the recipient, subject, body, and the SMTP server. Make sure to replace placeholder values like your.exchange.server.com, sender@Crescent.com, and recipient@Crescent.com with actual values relevant to your environment.

Method 5: Send Email with Send-MGUserMail cmdlet in Microsoft Graph

The Send-MGUserMail cmdlet is part of Microsoft.Graph.PowerShell module allows you to interact with the Microsoft Graph API via PowerShell. Assuming you have Microsoft.Graph PowerShell module installed already, and granted the “Mail.Send” permission to the app, Here is how you can use the Send-MGUserMail cmdlet to send emails.

#Connect to the Microsoft Graph serviceConnect-MgGraph# Define the email parameters$userId = "user@Crescent.com"$emailParameters = @{ ToRecipients = @( @{ EmailAddress = @{ Address = "recipient@Crescent.com" } } ) Subject = "Test Email from PowerShell" Body = @{ ContentType = "Text" Content = "Hello! This is a test email sent from PowerShell using Microsoft Graph." }}# Send the emailSend-MGUserMail -UserId $userId -Message $emailParameters -SendMail

In the example above:

  • $userId is the email address of the user on whose behalf the email will be sent.
  • $emailParameters is a hashtable that defines the email parameters like recipients, subject, and body.
  • The Send-MGUserMail cmdlet sends the email. The -SendMail parameter actually sends the email (as opposed to saving it as a draft).

More here: How to Send Password Expiration Reminder Email using Send-MgUserMail PowerShell cmdlet in Microsoft Graph?

Troubleshooting Common Issues

While sending emails from PowerShell can be straightforward, there are some common issues that may arise. In this section, we will discuss these issues and provide troubleshooting tips.

Issue: Authentication Failure

If you are experiencing authentication failures when sending email from PowerShell, double-check your credentials. Make sure you are using the correct username and password for the SMTP server you are trying to connect to.

Issue: SMTP Server Connection Failure

If you are unable to establish a connection to the SMTP server, ensure that the server’s URL or IP address is correct. Verify that you have network connectivity to the server and that any firewalls or security settings are not blocking the connection.

Issue: Email Not Being Delivered

If your email is not being delivered, check the spam or junk folder of the recipient’s email account. Sometimes, legitimate emails can be mistakenly flagged as spam. Additionally, ensure that the recipient’s email address is correct.

Issue: Missing Email Attachments

If you are trying to send email attachments using PowerShell, verify that the file paths are correct. Ensure that the files exist and are accessible by the script. Double-check that you are using the correct parameters to attach the files to the email.

Other common issues

While sending email in Office 365 with PowerShell is generally straightforward, you may encounter some common issues or errors along the way. Here are a few troubleshooting tips to help you resolve these issues:

  1. Ensure that you have the necessary permissions to send emails in Office 365. Check your user account’s role-based access control (RBAC) settings.
  2. Double-check the email addresses of the sender and recipient to ensure they are valid and correctly formatted.
  3. Verify that the SMTP server and port settings are accurate and compatible with Office 365’s requirements.
  4. Check if any firewalls or network restrictions are blocking the communication between your PowerShell script and Office 365 servers.
  5. Review the error messages or logs generated by PowerShell to identify any specific issues or errors.
  6. Validate the SSL/TLS certificate used by the SMTP server to ensure it is trusted by Office 365.
  7. Test your email sending script with a smaller number of recipients to identify any performance or scalability issues.

Remember, troubleshooting is an iterative process that may require some trial and error to identify and resolve specific issues. Patience and persistence are key when troubleshooting email sending issues in Office 365 with PowerShell.

Wrapping up

This comprehensive guide explored the art of sending emails from PowerShell. We covered how to send emails using PowerShell with Exchange and Gmail and how to include BCC and CC recipients. We also discussed common troubleshooting issues and provided best practices for sending emails from PowerShell. This comprehensive guide covers multiple real-world scenarios in detail, and equips you with the knowledge to leverage PowerShell for sending emails in various contexts.

By mastering the art of sending emails from PowerShell, you can streamline administrative tasks and improve communication with colleagues and clients. Whether you use Exchange or Gmail, PowerShell provides a flexible and powerful platform for automating email-sending processes. Sending email is a key way to extend PowerShell’s usefulness for real-world tasks. Hopefully, this guide gave you a good overview of the techniques. Please let me know in the comments if you have any other questions!

Related Posts

How to Send Emails in PowerShell using Send-MailMessage? (2024)
Top Articles
Latest Posts
Article information

Author: Dan Stracke

Last Updated:

Views: 5645

Rating: 4.2 / 5 (43 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Dan Stracke

Birthday: 1992-08-25

Address: 2253 Brown Springs, East Alla, OH 38634-0309

Phone: +398735162064

Job: Investor Government Associate

Hobby: Shopping, LARPing, Scrapbooking, Surfing, Slacklining, Dance, Glassblowing

Introduction: My name is Dan Stracke, I am a homely, gleaming, glamorous, inquisitive, homely, gorgeous, light person who loves writing and wants to share my knowledge and understanding with you.