Forum Discussion
Send-mailmessage not working in server
Hi Folks,
I'm trying to send an email via PowerShell using below code:
$TLS12Protocol = [System.Net.SecurityProtocolType] 'Ssl3 , Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $TLS12Protocol
$SecurePassword = ConvertTo-SecureString "password@123" -AsPlainText -Force
# Create a new PSCredential using the username and secure string password.
$Cred = New-Object System.Management.Automation.PSCredential ("email address removed for privacy reasons", $SecurePassword)
Send-MailMessage -SmtpServer smtp.office365.com -From email address removed for privacy reasons -To email address removed for privacy reasons -Subject testing -Body "Robocopy results are attached." -DeliveryNotificationOption onFailure -Credential $Cred -Port 587 -UseSsl
The above code works fine in my local machine. I receive the email as well. If I try to use the same in windows server. It does not work and throws the below error:
Send-MailMessage : The operation has timed out.
At line:8 char:1
+ Send-MailMessage -SmtpServer smtp.office365.com -From nmsautomation@o ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpException
+ FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage
I've been struggling with this for some days now. Could anyone please suggest some fixes I could try.
Thank you.
2 Replies
- farismalaebSteel Contributor
Timeout, are you sure that the tenant is enabled for Basic Auth.
Also make sure that the connection is allowed to connect to this port by the firewall.
Why are you using SSL3? It's dead, and Microsoft doesn't support it.
Get more info here
https://adamtheautomator.com/office-365-direct-send/
Test the connectivity by running
Test-NetConnection -ComputerName smtp.office365.com -Port 587
Also, why use the Send-MailMessage? it's obsolete and no longer supported, the cmdlet is archived. I think you need to use the Graph API to send emails.
https://helloitsliam.com/2021/10/18/sending-emails-using-microsoft-graph-powershell/
For more advance parameter of the Send-MgUserMail, check this
https://www.powershellcenter.com/2022/09/01/send-mgusermail/
- raindropsdevIron ContributorAdditionally, Basic Auth will be permanently disabled in 1 month, so not a good idea to start using it now.