Send MailMessage - PowerShell


Overview

Send-MailMessage lets you send email messages by transmitting SMTP commands to the specified SMTP server. It enables tailored message composition, authentication, and SSL/TLS encryption, making it versatile for sending emails from PowerShell scripts and workflows.

Syntax

Send-MailMessage [-To] <String[]> -From <String> -SmtpServer <String> -Subject <String> -Body <String> [-Cc] -Bcc -Port <Int32> [-UseSsl] [-Credentials <PSCredential>] [-Authentication <AuthenticationMechanism>]

Options/Flags

  • -To: Specifies recipients’ email addresses as an array of strings.
  • -From: Indicates the sender’s email address.
  • -SmtpServer: The name or IP address of the SMTP server.
  • -Subject: Sets the subject line of the email.
  • -Body: Accepts the email’s body content as a string.
  • -Cc: Options to add CC recipients, same usage syntax as -To.
  • -Bcc: Options to add BCC recipients, same usage syntax as -To.
  • -Port: Allows specification of the SMTP server’s port (default: 25).
  • -UseSsl: Enables SSL/TLS encryption when connecting to the SMTP server.
  • -Credentials: Uses the specified credentials object for authentication.
  • -Authentication: Sets the authentication mechanism to use (e.g., Basic, NTLM, Negotiate). Defaults to Basic.

Examples

Simple email:

Send-MailMessage -To user@example.com -From sender@example.com -SmtpServer smtp.example.com -Subject "Test Email" -Body "Hello from PowerShell!"

With CC and BCC:

Send-MailMessage -To primary@example.com -Cc secondary@example.com -Bcc third@example.com -From me@example.com -SmtpServer mail.example.com -Subject "Important Update" -Body "Details and instructions here."

Using authentication with SSL:

$credentials = Get-Credential -UserName username -Message "Enter credentials for SMTP server"
Send-MailMessage -To recipient@example.com -From myself@example.com -SmtpServer mailhost.example.com -Subject "Secure Email" -Body "Confidential information" -UseSsl -Credentials $credentials

Common Issues

  • SMTP server connectivity: Ensure your SMTP server is accessible and listening on the specified port.
  • Authentication errors: Verify the provided credentials are correct and authorized for email sending.
  • Port blocking: Make sure the SMTP server’s port (usually 25 or 587) is not blocked by a firewall or network security policy.

Integration

  • Use in conjunction with Get-SmtpServer command to retrieve SMTP server details.
  • Combine with ForEach-Object to send emails to multiple recipients from a list.
  • Integrate into Scheduled Tasks to automate email notifications.
  • Get-Credential
  • Write-Host