Friday, March 15, 2024

[O365] Send email in O365 via Powershell

 

$Recipient = "contact@domain.com"

$Subject = "Hello, World!"

$Body = "This is the body of the email."

$credentials = Get-Credential

Send-MailMessage -To $Recipient -Subject $subject -Body $body -From $credentials.UserName -SmtpServer "smtp.office365.com" -Port 587 -UseSsl -Credential $credentials


-----------------


Using saved/exported password:


# $credentials.Password | ConvertFrom-SecureString | out-file  L:\Downloads\senha.sec

$sen = Get-Content L:\Downloads\senha.sec | ConvertTo-SecureString

$us = "sender@mydomain.com"

$em = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $us,$sen

Send-MailMessage -To $Recipient -Subject $subject -Body $body -From $us -SmtpServer "smtp.office365.com" -Port 587 -UseSsl -Credential $em