carbonbase
asked on
sending email with PowerShell and Office365
Hi, I'm trying to send a welcome email to new Office365 mailboxes, the code I'm using connects to an Azure app registration which I've setup so I can run PowerShell scripts using certificates rather than having to specify usernames and passwords. I can then run the script as a scheduled task on one of my servers.
The code above, returns the following error when trying to send the email:
I've reviewed the following article on ways to send email in O365:
https://docs.microsoft.com/en-gb/Exchange/mail-flow-best-practices/how-to-set-up-a-multifunction-device-or-application-to-send-email-using-microsoft-365-or-office-365?redirectSourcePath=%252fen-us%252farticle%252fHow-to-set-up-a-multifunction-device-or-application-to-send-email-using-Office-365-69f58e99-c550-4274-ad18-c805d654b4c4#option2
Option 1 (SMTP Auth client submission) doesn't look like it would work for me as our accounts use MFA. Also I don't want to have to create a special mailbox for this or supply usernames or passwords in the script.
I tried option 2 (direct send) sounds like it may be an option for me as my script will only send email to mailboxes in my Office 365 tenant. But I'm not sure of the correct configuration/code I should use in my script. I tried it using this code which I found on the Internet:
but I got the following error:
What I'm looking for is a way to send email from an unattended PowerShell script to O365 mailboxes, and I am really keen not to have to specify any passwords in the script to do this. I've also read that it might be possible to do an api call in to Microsoft graph to do this? So would also welcome some advice around that if anyone has used Microsoft Graph to send emails generated by PowerShell scripts. Thanks.
# How to send a welcome message to new mailboxes using SMTP AUTH
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# Date to Check for new accounts - we use the last 7 days here, but that's easily changable.
[string]$CheckDate = (Get-Date).AddDays(-7)
## set the tenant ID (directory ID or domain)
$tenantID = '<MyCompany.onmicrosoft.com>'
## Set the Exchange Online Powershell Connections app id
$appID = '<my app id>'
## Set the certificate thumbprint
$CertificateThumbPrint = '<my cert thumbprint>'
## Connect to Exchange Online
Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint `
-AppID $appID `
-Organization $tenantID
$MsgFrom = "IT@mycompany.com" ; $SmtpServer = "smtp.office365.com" ; $SmtpPort = '587'
# Define some variables for the message
#HTML header with styles
$htmlhead="<html>
<style>
BODY{font-family: Arial; font-size: 10pt;}
H1{font-size: 22px;}
H2{font-size: 18px; padding-top: 10px;}
H3{font-size: 16px; padding-top: 8px;}
</style>"
#Header for the message
$HtmlBody = "<body>
<h1>Welcome to Our Company</h1>
<p><strong>Generated:</strong> $(Get-Date -Format g)</p>
<h2><u>We're Pleased to Have You Here</u></h2>"
# Find all mailboxes created in the target period
$Users = (Get-ExoMailbox -Filter "WhenMailboxCreated -gt '$CheckDate'" -RecipientTypeDetails UserMailbox -ResultSize Unlimited -Properties WhenMailboxCreated | Select WhenMailboxCreated, DisplayName, UserPrincipalName, PrimarySmtpAddress)
ForEach ($User in $Users) {
$EmailRecipient = $User.PrimarySmtpAddress
Write-Host "Sending welcome email to" $User.DisplayName
$htmlHeaderUser = "<h2>New User " + $User.DisplayName + "</h2>"
$htmlline1 = "<p><b>Welcome to Office 365</b></p>"
$htmlline2 = "<p>You can open Office 365 by clicking <a href=http://www.portal.office.com>here</a> </p>"
$htmlline3 = "<p>Have a great time and be sure to call the help desk if you need assistance.</p>"
$htmlbody = $htmlheaderUser + $htmlline1 + $htmlline2 + $htmlline3 + "<p>"
$HtmlMsg = "</body></html>" + $HtmlHead + $HtmlBody
# Construct the message parameters and send it off...
$MsgParam = @{
To = $EmailRecipient
From = $MsgFrom
Subject = "A Hundred Thousand Welcomes"
Body = $HtmlMsg
SmtpServer = $SmtpServer
Port = $SmtpPort }
Send-MailMessage @msgParam -UseSSL -BodyAsHTML
}
The code above, returns the following error when trying to send the email:
Send-MailMessage : The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 Client not authenticated to send mail
I've reviewed the following article on ways to send email in O365:
https://docs.microsoft.com/en-gb/Exchange/mail-flow-best-practices/how-to-set-up-a-multifunction-device-or-application-to-send-email-using-microsoft-365-or-office-365?redirectSourcePath=%252fen-us%252farticle%252fHow-to-set-up-a-multifunction-device-or-application-to-send-email-using-Office-365-69f58e99-c550-4274-ad18-c805d654b4c4#option2
Option 1 (SMTP Auth client submission) doesn't look like it would work for me as our accounts use MFA. Also I don't want to have to create a special mailbox for this or supply usernames or passwords in the script.
I tried option 2 (direct send) sounds like it may be an option for me as my script will only send email to mailboxes in my Office 365 tenant. But I'm not sure of the correct configuration/code I should use in my script. I tried it using this code which I found on the Internet:
## Build parameters
$mailParams = @{
SmtpServer = '<mycompany>.mail.protection.outlook.com'
Port = '25'
UseSSL = $true
From = 'it@mycompany.com'
To = 'user@mycompany.com'
Subject = "Direct Send $(Get-Date -Format g)"
Body = 'This is a test email using Direct Send'
DeliveryNotificationOption = 'OnFailure', 'OnSuccess'
}
## Send the email
Send-MailMessage @mailParams
but I got the following error:
Send-MailMessage : Mailbox unavailable. The server response was: 5.7.606 Access denied, banned sending IP <my public IP>
What I'm looking for is a way to send email from an unattended PowerShell script to O365 mailboxes, and I am really keen not to have to specify any passwords in the script to do this. I've also read that it might be possible to do an api call in to Microsoft graph to do this? So would also welcome some advice around that if anyone has used Microsoft Graph to send emails generated by PowerShell scripts. Thanks.
To remove your IP address from the banned list, you have to open your favorite browser and type the address https://sender.office.com. Enter the required information and click Submit.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks for the replies.
@David
I unblocked the IP yesterday, thank you.
@Vasil
Thanks for confirming what I suspected and for the link to that script. My plan is to add the the Graph Mail.Send permission to the Azure app that I setup to connect to Exchange Online with PowerShell. I'll also configure an access policy to limit the permission scope to a single mailbox.
@David
I unblocked the IP yesterday, thank you.
@Vasil
Thanks for confirming what I suspected and for the link to that script. My plan is to add the the Graph Mail.Send permission to the Azure app that I setup to connect to Exchange Online with PowerShell. I'll also configure an access policy to limit the permission scope to a single mailbox.
Another option is to set up a SMTP server on one of your servers, then you can use that to relay to Office 365. This is very handy when you have other devices that can't authenticate to send mail and various other scenarios. Then you can use Send-MailMessage which is much simpler than submitting through an API.
ASKER
@footech
We do still have on-prem Exchange so if it comes to it I could relay to that which would then send to the cloud mailboxes through the O365 connector. However, management are keen for a cloud solution and if it works, it's a good learning experience for me.
We do still have on-prem Exchange so if it comes to it I could relay to that which would then send to the cloud mailboxes through the O365 connector. However, management are keen for a cloud solution and if it works, it's a good learning experience for me.
ASKER
Thanks everyone for all your help on this.