Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save IT-Delinquent/04664f0412ac92bc6abc38ee0dd80d25 to your computer and use it in GitHub Desktop.

Select an option

Save IT-Delinquent/04664f0412ac92bc6abc38ee0dd80d25 to your computer and use it in GitHub Desktop.
PowerShell Code to Send a Custom HTML Email
#Define a valid SMTP server to send your emails through
$smtpServer = 'SERVER HERE' #e.g smtp.local.com
#Define a new SMTP object using the server defined above
$smtpObject = New-Object Net.Mail.SmtpClient($smtpServer)
#Create a new mail message object
$msg = New-Object Net.Mail.MailMessage
$msg.From = '[email protected]'
$msg.ReplyTo = '[email protected]'
$msg.BCC.Add('[email protected]')
$msg.To.Add('[email protected]')
$msg.subject = 'Example Email Subject'
$msg.IsBodyHtml = $True
$msg.Body = 'HTML FROM ABOVE - This can be a separate variable or right here'
#Provide a path to the photos for the email
$scriptPath = 'C:\example'
#Create a new mail attachment as an image
$logo = New-Object System.Net.Mail.Attachment -ArgumentList "$scriptPath\logo.png"
$logo.ContentDisposition.Inline = $True
$logo.ContentDisposition.DispositionType = "Inline"
$logo.ContentType.MediaType = "image/png"
$logo.ContentId = 'logo.png'
#Add the image attachment to the email, this allows the HTML to use the cid: prefix
$msg.Attachments.Add($logo)
#Try to send the email
try{
$smptObject.Send($msg)
}catch{
Write-Host 'Failed to send the email: ' -ForegroundColor Red -NoNewLine
Write-Host $Error[0] -ForegroundColor Red
}
#Dispose of the image attachments and the email object to avoid memory leaks
#logo.Dispose()
$msg.Dispose()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment