Skip to content

Instantly share code, notes, and snippets.

@cdsaenz
Created October 24, 2023 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdsaenz/384c81a97a7da73dc1c8b2d3c198ba4d to your computer and use it in GitHub Desktop.
Save cdsaenz/384c81a97a7da73dc1c8b2d3c198ba4d to your computer and use it in GitHub Desktop.
Send SMTP mail via 587 port and a hosting smtp server in Windows (Powershell)
$Username = "mysmtp-sender@mysmtpserver.com"
$Password = "mysmtp-sender-password"
$EmailTo = "willgetthetest@test.com"
$EmailFrom = "mysmtp-sender@mysmtpserver.com"
$Subject = "Test Email Powershell"
$Body = "Test Email content powershell"
$SMTPServer = "mail.mysmtpserver.com"
$SMTPClient = New-Object Net.Mail.SmtpClient
$SMTPClient.Host = $SMTPServer
$SMTPClient.Port = 587 # Port 587 is typically used with TLS
$SMTPClient.EnableSsl = $true # Enable TLS
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
$Message = New-Object Net.Mail.MailMessage
$Message.From = $EmailFrom
$Message.Subject = $Subject
$Message.Body = $Body
$Message.To.Add($EmailTo)
# Output a message before sending the email
Write-Host "Sending email..."
try {
$SMTPClient.Send($Message)
Write-Host "Email sent successfully."
}
catch {
Write-Host "Failed to send the email. Error: $($_.Exception.Message)"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment