Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aev-mambro2/0275e369818e89fc7d91e96a8d6129a4 to your computer and use it in GitHub Desktop.
Save aev-mambro2/0275e369818e89fc7d91e96a8d6129a4 to your computer and use it in GitHub Desktop.
powershell-send-email-via-ms-outlook-365-with-attachments
$who = New-Object System.Management.Automation.PSCredential(
"account@domain.there",
(ConvertTo-SecureString "TheSecret" -AsPlainText -Force)
) -ErrorAction Stop;
#NOTE: this version of Send-MailMessage does NOT have a -ReplyTo parameter.
Send-MailMessage `
-From account@domain.there `
-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 account@domain.here. `r`n"
)) `
-Attachments $files.ToArray([System.String]) `
-Port 587 `
-SmtpServer smtp.office365.com `
-UseSsl `
-ErrorAction Stop `
-Credential $who;
@aev-mambro2
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment