Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade

How to Send Emails Using Send-MailMessage in Windows PowerShell

The Send-MailMessage cmdlet in Windows PowerShell is a powerful tool for sending emails directly from the command line or within scripts. This cmdlet can be particularly useful for system administrators and developers who need to automate email notifications or alerts. Below, we will explore how to use Send-MailMessage with practical examples.

Examples:

  1. Basic Email Sending:

    To send a simple email, you need to specify the To, From, Subject, and Body parameters. You also need to specify an SMTP server using the -SmtpServer parameter.

    Send-MailMessage -To "recipient@example.com" -From "sender@example.com" -Subject "Test Email" -Body "This is a test email sent from PowerShell." -SmtpServer "smtp.example.com"
  2. Sending Email with Attachments:

    You can send an email with attachments by using the -Attachments parameter.

    Send-MailMessage -To "recipient@example.com" -From "sender@example.com" -Subject "Email with Attachment" -Body "Please find the attachment." -Attachments "C:\path\to\file.txt" -SmtpServer "smtp.example.com"
  3. Using Credentials for Authentication:

    If your SMTP server requires authentication, you can use the -Credential parameter to specify the credentials.

    $credential = Get-Credential
    Send-MailMessage -To "recipient@example.com" -From "sender@example.com" -Subject "Authenticated Email" -Body "This email uses SMTP authentication." -SmtpServer "smtp.example.com" -Credential $credential
  4. Sending HTML Emails:

    To send an HTML email, set the -BodyAsHtml parameter to $true.

    $htmlBody = "<h1>This is a test email</h1><p>This email contains HTML formatting.</p>"
    Send-MailMessage -To "recipient@example.com" -From "sender@example.com" -Subject "HTML Email" -Body $htmlBody -BodyAsHtml $true -SmtpServer "smtp.example.com"
  5. Using Different Ports:

    If your SMTP server uses a port other than the default (25), you can specify it using the -Port parameter.

    Send-MailMessage -To "recipient@example.com" -From "sender@example.com" -Subject "Email on Custom Port" -Body "This email is sent using a custom SMTP port." -SmtpServer "smtp.example.com" -Port 587

Note: The Send-MailMessage cmdlet is available in PowerShell 2.0 and later versions. However, it's important to note that this cmdlet is considered deprecated in newer versions of PowerShell and may be removed in future releases. Alternatives such as using the MailKit or System.Net.Mail .NET libraries are recommended for more robust email-sending capabilities.

To share Download PDF

Gostou do artigo? Deixe sua avaliação!
Sua opinião é muito importante para nós. Clique em um dos botões abaixo para nos dizer o que achou deste conteúdo.