I need to send a mail without any mail client (and I'm not a spammer !)

I need to send a mail without any mail client (and I'm not a spammer !)
Photo by Joanna Kosinska / Unsplash

From time to time, some of my scripts need to fire off an email with specific metrics.
Since the need is coming from scripts running on Windows servers, I need a PowerShell snippet that crafts the email body from an HTML file and sends it through an external SMTP server (and please, with the use of SSL !).

Let's make it happen !
Fire-up PowerShell and let's go !

# Variable for sending parameters
$EmailFrom = "sender@domaine.fr"
$EmailTo = "receiver@domaine.com"
$EmailBcc = "copy@domaine.net"
$Subject = "my notification email"
$SMTPServer = "smtp.server.com"
$SMTPPort = 587
$Username = "user allow to send thru this smtp"
$Password = "your-beautiful-password"
$HTMLBodyPath = "path to my mail.html"

# HTML fil to email body with UTF-8 encoding
$Body = Get-Content -Path $HTMLBodyPath -Encoding UTF8 -Raw

# build the mail 
$MailMessage = New-Object System.Net.Mail.MailMessage
$MailMessage.From = $EmailFrom
$MailMessage.To.Add($EmailTo)
$MailMessage.Bcc.Add($EmailBcc)
$MailMessage.Subject = $Subject
$MailMessage.Body = $Body
$MailMessage.IsBodyHtml = $true

# SMTP client setup
$SMTPClient = New-Object Net.Mail.SmtpClient($SMTPServer, $SMTPPort)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)

# sending email
try {
    $SMTPClient.Send($MailMessage)
    Write-Host "email was sent sucessfully"
} catch {
    Write-Error "Email sending failed $_"
}

Misuse this script for evil, and your karma will tank— you'll come back as a bonsai tree, pruned every morning ! 🌳✂️
Choose wisely!
😘