troubleshooting Question

sending email with PowerShell and Office365

Avatar of carbonbase
carbonbaseFlag for United Kingdom of Great Britain and Northern Ireland asked on
PowershellMicrosoft 365
6 Comments1 Solution36 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 = '<>'

## 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 = "" ; $SmtpServer = "" ; $SmtpPort = '587'

# Define some variables for the message
#HTML header with styles
      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;}
#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=>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

Open in new window

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

Open in new window

I've reviewed the following article on ways to send email in O365:
 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>'
    Port                       = '25'
    UseSSL                     = $true   
    From                       = ''
    To                         = ''
    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

Open in new window

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>

Open in new window

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 our community to see this answer!
Unlock 1 Answer and 6 Comments.
Start Free Trial
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