Powershell Email Function with SSL, HTML and Attachments

Use this forum if you have problems with a hMailServer script, such as hMailServer WebAdmin or code in an event handler.
Post Reply
palinka
Senior user
Senior user
Posts: 2189
Joined: 2017-09-12 17:57

Powershell Email Function with SSL, HTML and Attachments

Post by palinka » 2020-10-03 15:21

Powershell email function that includes everything you need in an email sending client: SSL, HTML and attachments.

Code: Select all

###   EMAIL VARIABLES   ###
$FromAddress      = 'sender@mydomain.tld'
$Recipient        = 'recipient@otherdomain.tld'
$Subject          = 'Powershell Email Function With SSL, HTML and Attachment Handling'
$EmailBody        = 'C:\scripts\EmailBody.txt'
$FileAttachment   = 'C:\scripts\somefile.log'
$HTML             = $True
$SMTPServer       = 'mail.domain.tld'
$SMTPAuthUser     = 'sender@mydomain.tld'
$SMTPAuthPass     = 'supersecretpassword'
$SMTPPort         = 587
$SSL              = $False

Function EmailResults {
	$Body = (Get-Content -Path $EmailBody | Out-String )
	If (Test-Path $FileAttachment){$Attachment = New-Object System.Net.Mail.Attachment $FileAttachment}
	$Message = New-Object System.Net.Mail.Mailmessage $FromAddress, $Recipient, $Subject, $Body
	$Message.IsBodyHTML = [System.Convert]::ToBoolean($HTML)
	If (Test-Path $FileAttachment){$Message.Attachments.Add($FileAttachment)}
	$SMTP = New-Object System.Net.Mail.SMTPClient $SMTPServer,$SMTPPort
	$SMTP.EnableSsl = [System.Convert]::ToBoolean($SSL)
	$SMTP.Credentials = New-Object System.Net.NetworkCredential($SMTPAuthUser, $SMTPAuthPass); 
	$SMTP.Send($Message)
}

EmailResults

Post Reply