FoxtrotTheFox
FoxtrotTheFox

Reputation: 53

Parsing a file of email adresses to set email recipients

I'm trying to write a PowerShell script which parses a list of email addresses and send a mail to them.

The file is formatted this way:

[email protected]
[email protected]
[email protected]
...

I figured something like:

$recipients = Get-Content -Path MY_FILE.txt

$outlook = New-Object -ComObject Outlook.Application
$mail = $Outlook.CreateItem(0)

$mail.To = $recipients   # here's the problem
$mail.Subject = "MY_SUBJECT"
$mail.HTMLBody = "MY_HTML_BODY"
$mail.Send()

My problem, as you can see is: how can I assign the addresses in $recipients to $mail.To?

Upvotes: 0

Views: 112

Answers (3)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

When in doubt, read the documentation:

MailItem.To Property (Outlook)

Returns or sets a semicolon-delimited String list of display names for the To recipients for the Outlook item. Read/write.

[...]

Remarks

This property contains the display names only. The To property corresponds to the MAPI property PidTagDisplayTo. The Recipients collection should be used to modify this property.

Emphasis mine.

To send one mail to all recipients change this line:

$mail.To = $recipients

into this:

foreach ($addr in $recipients) {
    $mail.Recipients.Add($addr)
}

and the code should do what you want.

Upvotes: 1

Razorfen
Razorfen

Reputation: 433

You could try something like this:

$file = "$PSScriptRoot\MY_FILE.txt"

# Add a List of recipients
$to = @()
foreach ($email in (Get-Content $file)) {
    $to += "$email;"
}
Write-Host "Complete recipient-list: $to"


$outlook = New-Object -ComObject Outlook.Application
$mail = $Outlook.CreateItem(0)
$mail.To = "$to"
$mail.Subject = "MY_SUBJECT"
$mail.HTMLBody = "MY_HTML_BODY"
$mail.Send()

Upvotes: 0

Gridonyx
Gridonyx

Reputation: 191

If you want to send every address in your file a separate email do it this way:

$recipients = Get-Content -Path MY_FILE.txt
$outlook = New-Object -ComObject Outlook.Application

ForEach ($recipient in $recipients) {
    $mail = $Outlook.CreateItem(0)
    $mail.To = $recipient
    $mail.Subject = "MY_SUBJECT"
    $mail.HTMLBody = "MY_HTML_BODY"
    $mail.Send()
}

Also make sure you close the COM Object by adding the following to the end of your file:

$outlook.Quit() 
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($outlook) | Out-Null

Upvotes: 0

Related Questions