Laeeq Qazi's Exchange Server Blog

Exchange Server blog

Send Email via PowerShell cmdlet Send-MailMessage

## Start of Scirpt ##

##This script reads Recipinets and Email Contents from 2 different text files
##And then sends email to all of the recipients

$cred =Get-Credential;
$smtpServer = “smtpServer.domain.com”

$Mailboxes = Get-Content c:\mailboxes.txt
$Email = Get-Content c:\Email.txt

$Contents = “”;
$Sender = “Admin@domain.com”;

foreach($row in $Email){$Contents+= $row};

foreach($mailbox in $Mailboxes)
{
$mailbox = $mailbox.Trim();
$mailbox;
$sub = “Hi $mailbox “;
$From = $Sender;

$To= $mailbox;
$body= $Contents;

if($To -ne $null -and $To -ne ”)
{
send-mailmessage -from $From -to $To -subject $sub -credential $cred -body $body -smtpServer $smtpServer
}
}

## End of Scirpt ##

This script uses powerShell 2.0 command send-mailmessage to send the mail message to various recipients, who are placed in a text file , each recipient on a single line like this:

user@domain1.com

user@domain2.com

user@domain3.com etc.

Script reads the Email contents from text file too, which makes this script dynamic. I used this script while working a email extracting application for load testing.  I had to work on very heavy mailboxes, with 10,000+ emails, and I used this script with one other loop, to send 2000 emails via single command.

I hope it help you.

Regards,

Laeeq Qazi

December 7, 2011 Posted by | Uncategorized | 2 Comments