how to send an email in powershell
- User
how to send an email in powershell
Assistant
how to send an email in powershell
PowerShell provides several ways to send emails, including using the Send-MailMessage cmdlet (deprecated in newer versions) and the MailKit library (recommended for modern PowerShell).
# Basic example (works in Windows PowerShell, deprecated in PowerShell 7+)
Send-MailMessage -From "sender@example.com" -To "recipient@example.com" `
-Subject "Test Email" -Body "This is a test email sent from PowerShell" `
-SmtpServer "smtp.example.com" -Port 587 -Credential (Get-Credential) `
-UseSsl
First, install the MailKit module if you haven't already:
Install-Package MailKit -Force
Then use this script:
# Load the MailKit assembly
Add-Type -Path (Join-Path (Get-Package MailKit).Source "netstandard2.0\MailKit.dll")
Add-Type -Path (Join-Path (Get-Package MimeKit).Source "netstandard2.0\MimeKit.dll")
# Create the email message
$message = [MimeKit.MimeMessage]::new()
$message.From.Add([MimeKit.MailboxAddress]::new("Sender Name", "sender@example.com"))
$message.To.Add([MimeKit.MailboxAddress]::new("Recipient Name", "recipient@example.com"))
$message.Subject = "Test Email from PowerShell"
$message.Body = [MimeKit.TextPart]::new("plain") {
Text = "This is a test email sent from PowerShell using MailKit"
}
# Configure and send the email
$client = [MailKit.Net.Smtp.SmtpClient]::new()
try {
$client.Connect("smtp.example.com", 587, [MailKit.Security.SecureSocketOptions]::StartTls)
$client.Authenticate("username", "password")
$client.Send($message)
Write-Host "Email sent successfully!" -ForegroundColor Green
}
catch {
Write-Host "Error sending email: $_" -ForegroundColor Red
}
finally {
$client.Disconnect($true)
$client.Dispose()
}
# Create the email message
$emailFrom = "sender@example.com"
$emailTo = "recipient@example.com"
$subject = "Test Email"
$body = "This is a test email sent from PowerShell using .NET"
# Create SMTP client
$smtpServer = "smtp.example.com"
$smtpPort = 587
$smtpUsername = "username"
$smtpPassword = "password"
$mailMessage = [System.Net.Mail.MailMessage]::new($emailFrom, $emailTo, $subject, $body)
$smtpClient = [System.Net.Mail.SmtpClient]::new($smtpServer, $smtpPort)
$smtpClient.EnableSsl = $true
$smtpClient.Credentials = [System.Net.NetworkCredential]::new($smtpUsername, $smtpPassword)
try {
$smtpClient.Send($mailMessage)
Write-Host "Email sent successfully!" -ForegroundColor Green
}
catch {
Write-Host "Error sending email: $_" -ForegroundColor Red
}
finally {
$mailMessage.Dispose()
$smtpClient.Dispose()
}
Get-Credential or secure strings instead of plain text passwordsWould you like me to explain any specific part in more detail?