# SMTP Server details
$smtpServer = "smtp.office365.com"
$smtpFrom = "user1@xyz.com"
$smtpTo = "user2@xyz.com"
$messageSubject = "Test Email"
$messageBody = "This is a test email sent using $hostname $Get_Date PowerShell."
#Current Date
$Get_Date = Get-Date
# Create a network credential object if required
$credentials = New-Object System.Net.NetworkCredential("user1@xyz.com", "Password")
# Create a new mail message
$mailmessage = New-Object system.net.mail.mailmessage
$mailmessage.from = ($smtpFrom)
$mailmessage.To.add($smtpTo)
$mailmessage.Subject = $messageSubject
$mailmessage.Body = $messageBody
$hostname = hostname
# Create an SMTP client with SSL/TLS support
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.EnableSsl = $true
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# Set credentials if required
$smtp.Credentials = $credentials
# Send the email
try {
$smtp.Send($mailmessage)
Write-Host "Email sent successfully!"
} catch {
Write-Host "Failed to send email: $_"
}
No comments:
Post a Comment