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
The code looks good. One thing which is not clear enough is setting a recipient for the outgoing email:
It is not clear what value is used in the code. To make sure the property is set correctly I'd suggest using the
Recipientsproperty of theMailItemclass instead. The Recipients.Add method creates a new recipient in theRecipientscollection. Then don't forget to use the Recipient.Resolve method which attempts to resolve aRecipientobject 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.