0

For logging tasks I need to send me an email through Outlook. I wrote some code like this:

$outlook = New-Object -ComObject Outlook.Application
$namespace = $outlook.GetNameSpace("MAPI")
$olFolders = "Microsoft.Office.Interop.Outlook.olDefaultFolders" -as [type]
$InboxDef = $namespace.GetDefaultFolder($olFolders::olFolderInBox)
$InboxDef.FullFolderPath -match "^\\\\(.*)\\Inbox$" | Out-Null
$recipient = $matches[1]
$email = $outlook.CreateItem(0)
$email.To = "$recipient"
$email.Subject = "Title"
$email.Body = "Text"
$email.Send()
$Outlook.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Outlook) | Out-Null

When I subsequently launch the Outlook client I see the email sent twice

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
  • 1
    I tried your code and it sends the message once. Is there some way that this could be called multiple times (e.g. is it in a loop, a function, etc)? Do you get the problem if you run just this code separate to anything else? – boxdog Oct 07 '22 at 08:33
  • This code is inserted into an if clause. Upstream such code I check if any Outlook client instance is active and I kill them in advance. The Oulook client is configured for multiple mail accounts, but I choose the default one (guessed from the GetDefaultFolder method) – Dario Corrada Oct 07 '22 at 08:43

1 Answers1

0

The code looks good. One thing which is not clear enough is setting a recipient for the outgoing email:

$InboxDef.FullFolderPath -match "^\\\\(.*)\\Inbox$" | Out-Null
$recipient = $matches[1]

It is not clear what value is used in the code. To make sure the property is set correctly I'd suggest using the Recipients property of the MailItem class instead. The Recipients.Add method creates a new recipient in the Recipients collection. Then don't forget to use the Recipient.Resolve method which attempts to resolve a Recipient object against the Address Book.

Read more about that in the article which I wrote for the technical blog, see How To: Fill TO,CC and BCC fields in Outlook programmatically.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45