Created
January 3, 2022 13:44
-
-
Save aev-mambro2/0275e369818e89fc7d91e96a8d6129a4 to your computer and use it in GitHub Desktop.
powershell-send-email-via-ms-outlook-365-with-attachments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$who = New-Object System.Management.Automation.PSCredential( | |
"[email protected]", | |
(ConvertTo-SecureString "TheSecret" -AsPlainText -Force) | |
) -ErrorAction Stop; | |
#NOTE: this version of Send-MailMessage does NOT have a -ReplyTo parameter. | |
Send-MailMessage ` | |
-From [email protected] ` | |
-Subject $("{0} Reports, dd. {1}" -f $files_count, $now) ` | |
-To undisclosed recipients ` | |
-Body $([System.String]::Concat( | |
"Please find attached your $($files_count) report$($plural_s): `r`n `r`n", | |
($files -Join ", `r`n"), | |
" `r`n `r`n", | |
"-- `r`n", | |
"For support and feedback, contact [email protected]. `r`n" | |
)) ` | |
-Attachments $files.ToArray([System.String]) ` | |
-Port 587 ` | |
-SmtpServer smtp.office365.com ` | |
-UseSsl ` | |
-ErrorAction Stop ` | |
-Credential $who; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It took a while to figure out how to send emails via Microsoft Outlook 365. This largely is Microsoft's fault, for refusing to adhere to standard SMTP practices. Salient points here are the port number (587), the SMTP server address, and the switch to use SSL.
Important too is the use of a specific PSCredential object. Its authentication must be set to an existing pre-qualified email user account. Additionally, to prevent your emails from getting blocked by Microsoft's spambot blocker, tell your Office 365 mail settings to allow that user account to be used as an emailer / from address.
Warning: using automated emailers may get your domain blocked and blacklisted by spam blockers. Be courteous.