Saturday, 5 September 2009

Send-EmailMessage.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script creates and sends an SMTP email message. 
  4. .DESCRIPTION 
  5.     This script first creates a System.Net.Mail.Mailmessage, and populates 
  6.     it. Next, it creates an system.Net.Mail.SmtpClient, which then sends 
  7.     the message to the SMTP Server, and onwards transmission. This script 
  8.     is effectively a re-write of the C# sample above. 
  9. .NOTES 
  10.     File Name  : Send-EmailMessage.ps1 
  11.     Author     : Thomas Lee - tfl@psp.co.uk 
  12.     Requires   : PowerShell V2 
  13. .LINK 
  14.     This script posted to: 
  15.         http://pshscripts.blogspot.com/2009/09/send-emailmessageps1.html
  16.     MSDN Sample posted at: 
  17.         http://msdn.microsoft.com/en-us/library/67w4as51.aspx 
  18. .EXAMPLE 
  19.     PSH [C:\foo]: .\Send-EmailMessage.ps1' 
  20.     Message sent successfully 
  21. #> 
  22.   
  23. ## 
  24. # Start of Script 
  25. ## 
  26.   
  27. # Set contents of the Email message 
  28. $To      = "doctordns@gmail.com" 
  29. $From    = "jane@cookham.net" 
  30. $Subject = "Using the .NET SMTP client." 
  31. $Body    = "Using this .NET feature, you can send an e-mail message from an application very easily." 
  32.               
  33. # Create meil message 
  34. $Message = New-Object System.Net.Mail.MailMessage $From, $To, $Subject, $Body 
  35.   
  36. # Create SMTP client 
  37. $Server = "cookham8" 
  38. $Port = 25 
  39. $Client = New-Object System.Net.Mail.SmtpClient $Server, $Port 
  40.   
  41. # Credentials are necessary if the server requires the client  
  42. # to authenticate before it will send e-mail on the client's behalf. 
  43. $Client.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials 
  44.   
  45. # Try to send the message 
  46. try { 
  47.        $Client.Send($Message
  48.        "Message sent successfully" 
  49.    
  50. # Catch an error 
  51. catch { 
  52. "Exception caught in Send-Emailmessage.ps1" 
  53. # End of Script 

1 comment:

hiro said...

Nice to meet you.

I was going to paste the link without permission because I had very felt the interest for your blog.

Please link me with the blog if it is good.

URL:http://hiro-anniversary.blogspot.com/

E-Mail:h-mori@ibs-office.com