Skip to content

Category: PowerShell

How to Send Emails with PowerShell

  1. Define email parameters:
    • $From: Specifies the sender’s email address.
    • $To: Specifies the recipient’s email address.
    • $Subject: Specifies the subject of the email.
    • $Body: Specifies the body content of the email.
    • $SMTPServer: Specifies the SMTP server address for sending the email.
    • $SMTPPort: Specifies the port number of the SMTP server.
    • $SMTPUsername: Specifies the username for authenticating with the SMTP server.
    • $SMTPPassword: Specifies the password for authenticating with the SMTP server.
  2. Create a credential object:
    • The New-Object cmdlet creates a new instance of a .NET object.
    • System.Management.Automation.PSCredential is the type of object being created, representing a credential object.
    • The -ArgumentList parameter is used to pass arguments to the constructor of the PSCredential object. In this case, it takes the SMTP username and a secure string of the SMTP password.
  3. Send the email:
    • The Send-MailMessage cmdlet is used to send the email.
    • Parameters such as -From, -To, -Subject, -Body, -SmtpServer, -Port, -Credential, and -UseSsl are used to specify the email details and SMTP server settings.
    • -Credential parameter is used to provide the credential object created earlier for authenticating with the SMTP server.
    • -UseSsl parameter specifies whether to use SSL/TLS encryption when connecting to the SMTP server.

By executing this PowerShell script, you’ll be able to send an email with the specified content to the specified recipient using the provided SMTP server credentials. Make sure to replace the placeholder values (like sender@example.com, recipient@example.com, etc.) with your actual email addresses and SMTP server details.

Define email parameters

$From = "sender@example.com"<br>$To = "recipient@example.com"<br>$Subject = "Test Email"<br>$Body = "This is a test email sent from PowerShell."<br>$SMTPServer = "smtp.example.com"<br>$SMTPPort = 587<br>$SMTPUsername = "your_smtp_username"<br>$SMTPPassword = "your_smtp_password"

Create a credential object

$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $SMTPUsername, (ConvertTo-SecureString -String $SMTPPassword -AsPlainText -Force)

Send the email

Send-MailMessage -From $From -To $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Port $SMTPPort -Credential $Credential -UseSsl 

Affiliate Disclosure

Please be advised that some of the links you encounter on our site are affiliate links. This means that if you click on them and make a purchase, we may earn a commission. Rest assured, we only link to sites and products we use and believe in. We strive for transparency and want you to know that our content may contain affiliate links.