Retry Sending Failed Email

I have a new starter script that sends a welcome email but sometimes the welcome email doesn’t send as the mailbox doesn’t get provisioned in time in Office 365. I have a do while loop to check that the script can find the mailbox in Office 365 but the mail still fails to send sometimes. I did some research online but couldn’t get it working. This is what I have so far:

#Email Parameters
$sendMailMessageSplat = @{

Subject = "Welcome, $firstname $lastname!"
From = 'welcome@domain.com'
To = $smtpaddress
#Bcc = 'support@domain.com'
SmtpServer = 'office365relayaddress'
Body = $htmltemplate3
}

#Sending email

try {
Send-MailMessage @sendMailMessageSplat -BodyAsHtml -EA Stop;

}
catch { Write-Host $sendErr
Sleep 10
Send-MailMessage @sendMailMessageSplat -BodyAsHtml
}

Exit

No reason to struggle at this or start from scratch. There are plenty of examples/sample code of this use case all over the web.
Simply searching for ‘send-mailmessage check for success’, will give you a good list of them.

You can also, check the O365 logs and get a report on the Send-Connector to see if it made it out. There is also, Message trace, and checking the SMTP logs.

Thanks for the response. I know the mail fails and the reason why - the mailbox isn’t provisioned yet. However, I’d like the script to keep trying until the mail succeeds. I have tried the below but with no success. I just can’t get it to keep trying.

function SendMailError {
$sendMailMessageSplat = @{

Subject = "Welcome, $firstname $lastname!"
From = 'welcome@ertosunhouse.com'
To = $smtpaddress
#Bcc = 'support@ertosunhouse.com'
SmtpServer = 'ertosunhouse-com.mail.protection.outlook.com'
Body = $htmltemplate3
}

try {
Send-MailMessage @sendMailMessageSplat -BodyAsHtml
}
catch {Write-Host $SendMailError
Start-Sleep 60
Send-MailMessage @sendMailMessageSplat -BodyAsHtml}

Exit
}

This doesn’t exactly answer your question, but it provides an alternate path. Earlier on in your account creation script you could do the error handling there, here is what I did for my user provisioning script. The 90 second sleep timer was put in place as that is how long I found for the mailbox to be provisioned once I kicked off a delta sync.

[pre]

New-RemoteMailbox -UserPrincipalName $upn -FirstName $firstname -LastName $lastname -DisplayName $displayname -Name $displayname -OnPremisesOrganizationalUnit $OU -Password $Password | Out-Null

Write-Host “Please wait while I run a delta Sync”

Start-DeltaSync

Write-Host “Waiting 90 seconds for user to show up in O365”
Start-Sleep -s 90

Write-host “Verifying user is in O365”

Do

{

Get-MsolUser -UserPrincipalName $upn -ErrorAction SilentlyContinue -ErrorVariable o365error | Out-Null

}

Until (!$o365error)
[/pre]