Powershell: Send mail with attachment 【Update】

$sender = "sender@company.com"
$recipient = "recipient@company.com"
$server = "<<SMTP Server>>"

$date = get-date
$file = "D:\test.txt"

$msg = new-object System.Net.Mail.MailMessage
$msg.From = $sender
$msg.To.Add($recipient)
$msg.Subject = "Sending a File " + $date.tostring("yyyy-MM-dd HH:mm:ss")
$msg.Body = "I'm sending a file!"
$fileStream = new-object System.IO.FileStream $file, "Open", "Read"
$ct = new-object System.Net.Mime.ContentType "text/plain; charset=iso-8859-1"
$attachment = new-object System.Net.Mail.Attachment $fileStream, $ct
$msg.Attachments.Add($attachment)
$client = new-object System.Net.Mail.SmtpClient $server
$client.Credentials = new-object System.Net.NetworkCredential "sender@company.com", "<<PASSWORD>>"
$client.EnableSsl = "true"
$client.Send($msg)

如果無需驗證用戶的話,那么可以將 Credential 設置為 [System.Net.CredentialCache]::DefaultNetworkCredentials 。并將 EnaleSsl 設置為 “false” 。

posted @ 2009-07-06 15:43 David Views(...) Comments(...) Edit 收藏
Freelance Jobs