Sending email once

45 views Asked by At

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

1

There are 1 answers

1
Eugene Astafiev On

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.