troubleshooting Question

sending email with PowerShell and Office365

Avatar of carbonbase
carbonbaseFlag for United Kingdom of Great Britain and Northern Ireland asked on
Microsoft 365Powershell
6 Comments1 Solution34 ViewsLast Modified:
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.

# 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.
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 6 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 6 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros