Sunday 18 January 2009

Send-BCCMail.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     Send mail to BCC using PowerShell 
  4. .DESCRIPTION 
  5.     This script is a re-developed MSDN Sample using PowerShell. It creates 
  6.     an email message then sends it with a BCC. 
  7. .NOTES 
  8.     File Name  : Send-BCCMail.ps1 
  9.     Author     : Thomas Lee - tfl@psp.co.uk 
  10.     Requires   : PowerShell V2 CTP3 
  11. .LINK 
  12.     Original Sample Posted to 
  13.     hthttp://pshscripts.blogspot.com/2009/01/send-bccmailps1.html 
  14.     MSDN Sample and details at: 
  15.     http://msdn.microsoft.com/en-us/library/system.net.mail.mailaddresscollection.aspx 
  16. .EXAMPLE 
  17.     PS C:\foo> .\Send-BCCMail.ps1 
  18.     Sending an e-mail message to The PowerShell Doctor and "Thomas Lee" <tfl@reskit.net> 
  19. #> 
  20.  
  21. ### 
  22. # Start Script 
  23. ### 
  24.  
  25. # Create from, to, bcc and the message strucures 
  26. $From    = New-Object system.net.Mail.MailAddress "tfl@cookham.net", "Thomas Lee" 
  27. $To      = new-object system.net.mail.Mailaddress "doctordns@gmail.com", "The PowerShell Doctor" 
  28. $Bcc     = New-Object system.Net.Mail.Mailaddress "tfl@reskit.net", "Thomas Lee" 
  29. $Message = New-Object system.Net.Mail.MailMessage $From, $To 
  30.  
  31. # Populate message 
  32. $Message.Subject = "Using the SmtpClient class and PowerShell." 
  33. $Message.Body    = "Using this feature, you can send an e-mail message from an" 
  34. $Message.Body   += "application very easily. `nEven better, you do it with PowerShell!" 
  35.  
  36. # Add BCC 
  37. $Message.Bcc.Add($bcc); 
  38.  
  39. # Create SMTP Client 
  40. $Server = "localhost" 
  41. $Client = New-Object system.Net.Mail.SmtpClient $server 
  42. $Client.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials 
  43. "Sending an e-mail message to {0} and {1}" -f $to.DisplayName, $Message.Bcc.ToString() 
  44.  
  45. # send the message 
  46. try { 
  47.     $Client.Send($message); 
  48. }   
  49. catch { 
  50. "Exception caught in Send-BCCMail.ps1: {0}" -f $Error[0] 
  51.        

No comments: