Monday, February 27, 2006

 
Sending email using MSH part 2

Thanks to MOW at microsoft.public.windows.server.scripting newsgroup. There is an easier way to send email.


$smtp = new-object Net.Mail.SmtpClient("smtp.nospam.com")
$smtp.send("someone@nospam.com","someone@nospam.com", "Email using MSH", "This is easy.")


This example works well when the computer is within the subnet of the email SMTP server. However, I cannot run this at home, because there are more restrictions. For example, we need to enable SSL and also we need to supply credential to send messages outside our network. Here is another example to enable SSL and use credential.


$smtp = new-object Net.Mail.SmtpClient
$smtp.Host = "smtp.nospam.com"
$smtp.EnableSsl = $true
$smtp.Credentials = new-object Net.NetworkCredential("username", "password")
$smtp.send("someone@nospam.com","someone@nospam.com", "Email using MSH", "This is easy.")


If you need to send attachment and you also want to BCC(or CC) other people, you'll need to use another class: System.Net.Mail.MailMessage. Here is another example.


$smtp = new-object Net.Mail.SmtpClient
$smtp.Host = "smtp.nospam.com"
$smtp.EnableSsl = $true
$smtp.Credentials = new-object Net.NetworkCredential("username", "password")

$msg = new-object Net.Mail.MailMessage
$msg.From = "someone@nospam.com"
$msg.To.Add("someone@nospam.com")
$msg.Bcc.Add("someone@gmail.com")
$msg.Subject = "Full test"
$msg.Body = "This is a full test"
$att = new-object Net.Mail.Attachment("c:\testfile.txt")
$msg.Attachments.Add($att)

$smtp.Send($msg)

Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?