In this particular example, we are looking to send a HTML website (which in this case is a report that’s been generated by scripting or automation) and that HTML file needs to be the body of the email rather than a simple attachment.
You need to ensure that the file is correctly formatted HTML - you can check that with your browser of choice, which should obviously be Chrome.
When you are happy with what you’re about to send out, you can simply use the script below, remembering to update the HTML file name in the script.
Script : HTML-SMTP.ps1
# Email configuration
$smtpServer = "smtp.bear.local"
$smtpPort = 25
$fromEmail = "mac.caching@croucher.cloud"
# Array of recipients
$toEmails = @(
"lee@croucher.cloud",
"cbo@croucher.cloud"
)
$subject = "Bears are Awesome"
# Read HTML content from file
try {
$htmlBody = Get-Content -Path "cache_report.html" -Raw
if ($null -eq $htmlBody) {
throw "File is empty"
}
} catch {
Write-Host "Error reading HTML file: $_"
exit 1
}
# Create mail message
$mailMessage = New-Object System.Net.Mail.MailMessage
$mailMessage.From = $fromEmail
foreach ($recipient in $toEmails) {
$mailMessage.To.Add($recipient)
}
$mailMessage.Subject = $subject
$mailMessage.IsBodyHtml = $true
$mailMessage.Body = $htmlBody
# Create SMTP client
$smtpClient = New-Object System.Net.Mail.SmtpClient($smtpServer, $smtpPort)
$smtpClient.EnableSsl = $false
$smtpClient.Credentials = $credential
# Send email
try {
$smtpClient.Send($mailMessage)
Write-Host "Email sent successfully to all recipients!"
} catch {
Write-Host "Error sending email: $_"
} finally {
$mailMessage.Dispose()
$smtpClient.Dispose()
}