Send SMTP Mail Message Using PowerShell and .NET


posted by Thomas Lee
11-24-2008

Downloads: 1,236
File size: 978 B
Views: 25,254

Embed
Send SMTP Mail Message Using PowerShell and .NET
  1. # Send-SMTPMessage.ps1 
  2. # MSDN Sample, recoded using PowerShell 
  3. # Thomas Lee - tfl@psp.co.uk 
  4.  
  5. # Create from/to addresses 
  6. $from = New-Object System.Net.Mail.MailAddress "powershell@psp.co.uk" 
  7. $to =   New-Object System.Net.Mail.MailAddress "doctordns@gmail.com" 
  8.  
  9. # Create Message 
  10. $message = new-object  System.Net.Mail.MailMessage $from, $to 
  11. $message.Subject = "Using the SmtpClient class and PowerShell" 
  12. $message.Body = @" 
  13. Using this feature, you can send an e-mail message from an application very easily. 
  14. "@ 
  15.  
  16. # Set SMTP Server and create SMTP Client 
  17. $server = "localhost" 
  18. $client = new-object system.net.mail.smtpclient $server 
  19.  
  20. # Send the message 
  21. "Sending an e-mail message to {0} by using SMTP host {1} port {2}." -f $to.ToString(), $client.Host, $client.Port 
  22. try { 
  23.    $client.Send($message
  24.    "Message to: {0}, from: {1} has beens successfully sent" -f $from, $to 
  25. catch { 
  26.   "Exception caught in CreateTestMessage: {0}" -f $Error.ToString() 

This script uses the .NET Classes System.Net.Mail.Mailmessage, System.Net.Mail.MailAddress and System.Net.Mail.SMTPClient to format and send a SMTP message to a SMTP Server.

Note that this script uses LocalHost as the SMTP host operating on Port 25 (in my case, this is correct). You may need to adjust this in your own environment.

Comments

calli wrote re: Send SMTP Mail Message Using PowerShell and .NET
on 09-09-2009 5:44 AM

Hi,

to send email with PowerShell is pretty easy, fine, but is it that easy to access e.g.my mailbox at google (http://mail.google.com => my..c@gmail.com + PWD) to download some selectedd emails from there?

I haven't found anything anywhere. That was all for outlook account or Win.Server.. :(

Thanks in advance,

calli

calli wrote re: Send SMTP Mail Message Using PowerShell and .NET
on 09-09-2009 7:52 AM

let me add a bit,

I'd like to do a POP3 access:

@: pop.googlemail.com

witth SSL

& Port: 995

Thomas Lee wrote re: Send SMTP Mail Message Using PowerShell and .NET
on 09-09-2009 9:12 AM

I''ve not seen any POP3 client type classes in the .NET Framework.

Richard Giles wrote re: Send SMTP Mail Message Using PowerShell and .NET
on 09-09-2009 10:11 AM

Check out NetCmdlets from n/Software. They have cmdlets for a variety of sources including POP, IMAP, IM SMS.

Thomas Lee wrote re: Send SMTP Mail Message Using PowerShell and .NET
on 09-09-2009 1:03 PM

Good point Richard - I was thinking just inside the .NET Framework.

Copyright 2012 PowerShell.com. All rights reserved.